gpt4 book ai didi

Java解密时出错

转载 作者:行者123 更新时间:2023-12-02 05:04:37 25 4
gpt4 key购买 nike

我有两个名为 Encryption.java 和 Decryption.java 的类。我想使用 encrypt.java 类加密文本文件并从解密.java 类解密。我可以成功加密文本文件,但无法以相同的方式解密它。谁能告诉我为什么不呢?

这是加密.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);
}

这是我的decrypt.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)

最佳答案

您使用 SecretKey SecKey = KeyGen.generateKey() 生成用于加密的 key ,这很好,但是当您解密时,您会尝试使用新 key ,而不是您以前使用的 key 加密文本。您需要保存 key ,以便可以使用它进行解密。

关于Java解密时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27900193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com