import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.UUID;
@Slf4j
public class RSAUtil {
private static final String RSA = "RSA";
private static final String PRIVATE_KEY = "privateKey";
private static final String PUBLIC_KEY = "publicKey";
private static final String ALGORITHM = "MD5withRSA";
private static final int ZERO = 0;
private static final int MAX_ENCRYPT_BLOCK = 117;
private static final int MAX_DECRYPT_BLOCK = 128;
private final static Map<String, String> KEY_MAP = Maps.newHashMap();
public static String getPublicKey() {
if (KEY_MAP.size() == ZERO) {
genKeyPair();
}
return KEY_MAP.get(PUBLIC_KEY);
}
public static String getPriKey() {
if (KEY_MAP.size() == ZERO) {
genKeyPair();
}
return KEY_MAP.get(PRIVATE_KEY);
}
@SneakyThrows
public static void genKeyPair() {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(RSA);
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
KEY_MAP.put(PUBLIC_KEY, publicKeyString);
KEY_MAP.put(PRIVATE_KEY, privateKeyString);
}
public static String encrypt(String str, String publicKey) throws Exception {
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(RSA).generatePublic(new X509EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
return Base64.encodeBase64String(cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)));
}
public static String decrypt(String str, String privateKey) throws Exception {
byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8));
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(RSA).generatePrivate(new PKCS8EncodedKeySpec(decoded));
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, priKey);
return new String(cipher.doFinal(inputByte));
}
public static String encryptSegment(String data, String pubKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
byte[] decodedKey = Base64.decodeBase64(pubKey.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int inputLen = data.getBytes().length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = ZERO;
byte[] cache;
int i = ZERO;
while (inputLen - offset > ZERO) {
if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
}
out.write(cache, ZERO, cache.length);
i++;
offset = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return Base64.encodeBase64String(encryptedData);
}
public static String decryptSegment(String data, String priKey) throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
byte[] decodedKey = Base64.decodeBase64(priKey.getBytes());
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
Cipher cipher = Cipher.getInstance(RSA);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] dataBytes = Base64.decodeBase64(data);
int inputLen = dataBytes.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offset = ZERO;
byte[] cache;
int i = ZERO;
while (inputLen - offset > ZERO) {
if (inputLen - offset > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
}
out.write(cache, ZERO, cache.length);
i++;
offset = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData, StandardCharsets.UTF_8);
}
public static String sign(String data, PrivateKey privateKey) throws Exception {
byte[] keyBytes = privateKey.getEncoded();
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PrivateKey key = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance(ALGORITHM);
signature.initSign(key);
signature.update(data.getBytes());
return new String(Base64.encodeBase64(signature.sign()));
}
public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
byte[] keyBytes = publicKey.getEncoded();
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(RSA);
PublicKey key = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(ALGORITHM);
signature.initVerify(key);
signature.update(srcData.getBytes());
return signature.verify(Base64.decodeBase64(sign.getBytes()));
}
public static void main(String[] args) {
try {
genKeyPair();
StringBuilder builder = new StringBuilder();
do {
builder.append(UUID.randomUUID().toString());
} while (builder.toString().length() <= 100);
String data = builder.toString();
System.out.println("data长度:" + data.length());
String encryptSegment = encryptSegment(data, getPublicKey());
System.out.println("加密后内容:" + encryptSegment);
System.out.println("加密后内容长度:" + encryptSegment.length());
String decryptSegment = decryptSegment(encryptSegment, getPriKey());
System.out.println("解密后内容:" + decryptSegment);
System.out.println("解密后内容长度:" + decryptSegment.length());
String encrypt = encrypt(data, getPublicKey());
System.out.println("加密后内容:" + encrypt);
System.out.println("加密后内容长度:" + encrypt.length());
String decrypt = decrypt(encrypt, getPriKey());
System.out.println("解密后内容:" + decrypt);
System.out.println("解密后内容长度:" + decrypt.length());
} catch (Exception e) {
e.printStackTrace();
System.out.print("加解密异常");
}
}
}