我的 RSA 解密有什么问题?
这是加密代码:
try {
//Get the public key from the keyStore and set up the Cipher object
PublicKey publicKey = getPubKey(keyStore,keyName);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.ENCRYPT_MODE, publicKey);
//Read the plainText
System.out.println("Loading plaintext file: "+inFile);
RandomAccessFile rawDataFromFile = new RandomAccessFile(inFile, "r");
byte[] plainText = new byte[(int)rawDataFromFile.length()];
rawDataFromFile.read(plainText);
// Generate a symmetric key to encrypt the data and initiate the AES Cipher Object
System.out.println("Generating AES key");
KeyGenerator sKenGen = KeyGenerator.getInstance("AES");
Key aesKey = sKenGen.generateKey();
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
// Encrypt the symmetric AES key with the public RSA key
System.out.println("Encrypting Data");
byte[] encodedKey = rsaCipher.doFinal(aesKey.getEncoded());
// Encrypt the plaintext with the AES key
byte[] cipherText = aesCipher.doFinal(plainText);
//Write the encrypted AES key and Ciphertext to the file.
System.out.println("Writting to file: "+outFile);
FileOutputStream outToFile = new FileOutputStream(outFile);
outToFile.write(encodedKey);
outToFile.write(cipherText);
System.out.println("Closing Files");
rawDataFromFile.close();
outToFile.close();
}
catch (Exception e) {
System.out.println("Doh: "+e);
}
这是我的解密代码,我认为它会很好地工作,但事实并非如此。任何人都可以帮助我吗?
它一直有错误:javax.crypto.BadPaddingException:解密错误
不知道该怎么办,有人可以给我一些建议吗?
private static void decryptRSA() {
try {
System.out.println("Loading plaintext file: "+inFile);
RandomAccessFile rawDataFromFile = new RandomAccessFile(inFile, "r");
byte[] cipherText = new byte[(int)rawDataFromFile.length()];
byte encodedkey[] = new byte[256];
rawDataFromFile.read(encodedkey, 0, 256);
rawDataFromFile.read(cipherText);
PublicKey publicKey = getPubKey(keyStore,keyName);
Cipher rsaCipher = Cipher.getInstance("RSA");
rsaCipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] aeskey = rsaCipher.doFinal(encodedkey);
SecretKeySpec aesKey = new SecretKeySpec(aeskey, "AES");
Cipher aesCipher = Cipher.getInstance("AES");
aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
byte[] plainText = aesCipher.doFinal(cipherText);
System.out.println("Writting to file: "+outFile);
FileOutputStream outToFile = new FileOutputStream(outFile);
outToFile.write(plainText);
System.out.println("Closing Files");
rawDataFromFile.close();
outToFile.close();
}
catch (Exception e) {
System.out.println("Doh: "+e);
}
}
最佳答案
RSA 解密是使用私钥而不是公钥完成的。
解密代码中
cipherText
数组的长度不正确。您应该减去 256,或者将实际读取长度传递给Cipher.doFinal()
,或者实际上两者都传递。
注意,尽管您正在打印消息,但您的解密步骤实际上是从密文文件中读取,而不是从明文文件中读取。
关于java - RSA 与 AES 加密和解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412749/