RSA多次加密同一原文密文都不一样?
RSA采用一对固定的公私匙加密同一原文每次的密文都不一样,是这样的么?
/**
* 解密
* 用私钥解密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, String key)
throws Exception {
// 对密钥解密
byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 对数据解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 加密
* 用公钥加密
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String key)
throws Exception {
// 对公钥解密
byte[] keyBytes = (new BASE64Decoder()).decodeBuffer(key);
// 取得公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicKey = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
public static void main(String[] args) throws Exception {
//其中PUB_VALUE PRI_VALUE 用(new BASE64Encoder()).encodeBuffer转String
RSACoder rsa =new RSACoder();
String str = "RSA加密";
byte[] data = str.getBytes("utf-8");
byte[] encodata = rsa.encryptByPublicKey(data, PUB_VALUE);
System.out.println("encodata:"+encodata);
String enbasePri = (new BASE64Encoder()).encodeBuffer(encodata);
byte[] encodataag = (new BASE64Decoder()).decodeBuffer(enbasePri);
byte[] decodata = rsa.decryptByPrivateKey(encodataag, PRI_VALUE);
System.out.println("加密前:"+str);
System.out.println("加密后:"+enbasePri);
System.out.println("解密后:"+new String(decodata,"utf-8"));
}
[解决办法]
使用一对固定的公私钥进行加解密,使用公钥对同一明文进行加密,每次运算的结果是同一密文。