RSA加解密:
@Log4j
public class RSAMorliaCipher implements IMorliaCipher{
private static final String RSA_PUB_KEY_STRING = "publickey";
private static final String RSA_PRI_KEY_STRING = "privatekey";
private static Cipher pubCipher = null;
private static Cipher priCipher = null;
static {
try {
//生成base64编码的公钥
byte[] decoded = Base64.decodeBase64(RSA_PUB_KEY_STRING);
RSAPublicKey publicKey2 = (RSAPublicKey) KeyFactory.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(decoded));
//RSA
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.PUBLIC_KEY, publicKey2);
pubCipher = cipher;
}catch (Exception e) {
log.error("RSA public key cipher init failed!!");
}
try {
//base64编码的私钥
byte[] decoded = Base64.decodeBase64(RSA_PRI_KEY_STRING);
RSAPrivateKey privateKey2 = (RSAPrivateKey) KeyFactory.getInstance("RSA")
.generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey2);
priCipher = cipher;
}catch (Exception e) {
log.error("RSA private key cipher init failed!!");
}
}
@Override
public String encrypt(String data, String key) throws Exception {
return Base64.encodeBase64String(pubCipher.doFinal(data.getBytes()));
}
@Override
public String decrypt(String data, String key) throws Exception {
return new String(priCipher.doFinal(Base64.decodeBase64(data.getBytes())));
}
public void generateKeyPair() throws NoSuchAlgorithmException {
//KeyPairGenerator类用于生成私钥和公钥对,基于RSA算法
KeyPairGenerator keyPairGenerat