【发布时间】:2018-01-23 23:52:59
【问题描述】:
我的 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: Decryption error
真的不知道该怎么办,谁能给我一些建议?
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);
}
}
【问题讨论】:
-
您应该阅读
RandomAccessFile的read方法的API 文档。您的文件处理不正确。
标签: java encryption cryptography aes rsa