RSA封装类 ,完整的RSA加密和解密
public class RSAUtilEncrypt {
public static final String KEY_ALGORTHM = "RSA";//
public static final String KEY_ALGORTHM_RSA_ECB_PKCS1PADDING = "RSA/ECB/PKCS1Padding";
public static String RSA_PUBLIC_KEY = "rsa_public_key";
public static String RSA_PRIVATE_KEY = "rsa_private_key";
private int KeySize = 1024;
private Map keyMap;
private static String RSA = "RSA";
private static PublicKey publickey;
public RSAUtilEncrypt(int KeySize,String publickey) {
this.KeySize = KeySize;
try {
this.publickey=generatePublicKeyByString(publickey);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private RSAPublicKey generatePublicKeyByString(String publicKeyStr)
throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("No Algorthm,Checked by cemung!");
} catch (InvalidKeySpecException e) {
throw new Exception("InvalidKeySpec!");
} catch (IOException e) {
throw new Exception("Io exception!");
} catch (NullPointerException e) {
throw new Exception("Illegle pointer reference!");
}
}
// Encypt
public byte[] RSAEncrypt(byte[] data, RSAPublicKey publickey)
throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING);
cipher.init(Cipher.ENCRYPT_MODE, this.publickey);
byte[] cipherbytes = cipher.doFinal(data);
return cipherbytes;
}
// Encypt
public byte[] RSAEncrypt(byte[] data)
throws Exception {
Cipher cipher = Cipher.getInstance(KEY_ALGORTHM_RSA_ECB_PKCS1PADDING);
cipher.init(Cipher.ENCRYPT_MODE, this.publickey);
byte[] cipherbytes = cipher.doFinal(data);
return cipherbytes;
2021-11-18 09:46:15
5KB
RSA加密
1