【发布时间】:2015-01-12 10:45:40
【问题描述】:
我有两个名为encryption.java 和decryption.java 的类。我想使用 encrypt.java 类加密文本文件并从 decrypt.java 类解密。我可以成功加密文本文件,但不能以同样的方式解密它。谁能告诉我为什么不呢?
这是 encrypt.java:
public class Encrypt{
public static void main(String[] args) throws Exception {
String FileName = "D:/ashok/normal.txt";
String FileName1 = "D:/ashok/encrypted.txt";
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey SecKey = KeyGen.generateKey();
Cipher AesCipher = Cipher.getInstance("AES");
byte[] cipherText = Files.readAllBytes(Paths.get(FileName));
AesCipher.init(Cipher.ENCRYPT_MODE, SecKey);
byte[] byteCipherText = AesCipher.doFinal(cipherText);
Files.write(Paths.get(FileName1), byteCipherText);
}
这是我的解密.java 类:
class decrypt{
public static void main(String[] args) {
try {
String FileName1 = "D:/ashok/encrypted.txt";
String FileName2 = "D:/ashok/decrypted.txt";
KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
KeyGen.init(128);
SecretKey SecKey = KeyGen.generateKey();
Cipher AesCipher = Cipher.getInstance("AES");
byte[] cipherrText = Files.readAllBytes(Paths.get(FileName1));
AesCipher.init(Cipher.DECRYPT_MODE, SecKey);
byte[] bytePlainText = AesCipher.doFinal(cipherrText);
Files.write(Paths.get(FileName2), bytePlainText); }}
解密类运行时出错,像这样
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:676)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:313)
at javax.crypto.Cipher.doFinal(Cipher.java:2086)
at decryption.main(decryption.java:79)
【问题讨论】:
-
用
keystoregithub.com/sufiyanghori/aes-256-java-bks试试这个AES-256实现
标签: java encryption cryptography