gpt4 book ai didi

java - 使用 AES-128 加密和解密字符串

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:33:12 25 4
gpt4 key购买 nike

我在加密 128 位 key 时得到它。我能做些什么来扭转这个过程。我几乎坐在这里将近一个小时来解决这个问题,但我做不到。顺便说一句,我是新手。

样本输入是:J§????????ÿK♥?{↕?

输出应该是:hello

在这个程序中:

示例输入是:hello

输出是:J§????????ÿK♥?{↕?...

public class en {
public static void main(String[] args){
...
try{
System.out.print("Enter text: ");
String text = dataIn.readLine();
String key = "dAtAbAsE98765432"; // 128 bit key

// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");

// encrypt the text
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
System.err.println("Encrypted: " + new String(encrypted));

// Decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println("Decrypted: " + decrypted);
}catch(Exception e){
e.printStackTrace();
}
}
}

最佳答案

密文由字节组成,应该看起来是随机的。你会得到不可打印的字符,你也不能输入。你必须使用像 Base64 这样的编码在加密后打印你的密文,并在解密前输入。

加密期间(Java 8):

cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(text.getBytes());
System.err.println("Encrypted: " + new String(Base64.getEncoder().encodeToString(encrypted)));

解密期间(Java 8):

System.out.print("Enter ciphertext: ");
byte[] encrypted = Base64.getDecoder().decode(dataIn.readLine());
...
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encrypted));
System.err.println("Decrypted: " + decrypted);

Encoding reference


除此之外,您真的应该完全指定您的方案,因为它可能在另一个 Java 实现上表现不同。

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

关于java - 使用 AES-128 加密和解密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28025742/

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