public static final String RSA_ALGORITHM = "RSA";
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
public static final Charset UTF8 = Charset.forName("UTF-8");
private static int MAX_ENCRYPT_BLOCK = 117;
//解密长度不超过128字节,密钥位数为2048时,最大解密长度应为256
private static int MAX_DECRYPT_BLOCK = 256;
//加密
public static String encrypt(String data, String publicKey) throws Exception {
String result = "";
try {
RSAPublicKey pubKey = loadPublicKey(publicKey);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] inputArray = data.getBytes(UTF8);
int inputLength = inputArray.length;
int offset = 0;
byte[] resultBytes = {};
byte[] cache = {};
while (inputLength - offset > 0) {
if (inputLength - offset > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(inputArray, offset, MAX_ENCRYPT_BLOCK);
offset += MAX_ENCRYPT_BLOCK;
} else {
cache = cipher.doFinal(inputArray, offset, inputLength - offset);
offset = inputLength;
}
resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
}
result = byteArrayToHex(resultBytes);
} catch (Exception e) {
log.error("rsaEncrypt error:{}", e.getMessage());
}
return result;
}
/**
* RSA私钥解密
*
* @param data 解密数据
* @param privateKey 私钥
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String data, String privateKey) throws Exception {
RSAPrivateKey priKey = loadPrivateKey(privateKey);
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] inputArray = hexToByteArray(data);
int inputLength = inputArray.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLength - offSet > 0) {
if (inputLength - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(inputArray, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
String outStr = new String(decryptedData,UTF8);
return outStr;
}
可以 参考这个博客
Java使用RSA的公钥加密,私钥解密;私钥加密,公钥解密_silangfeilang的博客-CSDN博客_java使用rsa公钥私钥加密解密