gpt4 book ai didi

java - 使用 AES 加密

转载 作者:行者123 更新时间:2023-12-01 10:46:56 25 4
gpt4 key购买 nike

我正在使用 AES 加密字符串,但它没有将“1234567812345678”字符从加密字符串解密回纯文本。对于其他文本(例如“Hello World”),它工作正常。还希望保持加密代码只接受 UTF-8 字符。我正在使用下面的代码

import java.security.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES
{

public static void main(String[] args)
{
//listing all available cryptographic algorithms

/* for (Provider provider: Security.getProviders()) {
System.out.println(provider.getName());
for (String key: provider.stringPropertyNames())
System.out.println("\t" + key + "\t" + provider.getProperty(key));
}*/
StrongAES saes = new StrongAES();
String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("1234567812345678"));
//String encrypt = saes.encrypt(new String("Bar12346Bar12346"),new String("Hello world"));
System.out.println(encrypt);
String decrypt = saes.decrypt(new String("Bar12346Bar12346"), new String(encrypt));
System.out.println(decrypt);
}


String encrypt(String key, String text)
{
String encryptedText="";
try{
// 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());
encryptedText = new String(encrypted);
// System.out.println(encryptedText);
}
catch(Exception e)
{
e.printStackTrace();
}
return encryptedText;

}

String decrypt(String key, String encryptedText)
{
String decryptedText="";
try{
// Create key and cipher
Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");

// decrypt the text
cipher.init(Cipher.DECRYPT_MODE, aesKey);
decryptedText = new String(cipher.doFinal(encryptedText.getBytes()));
// System.out.println("Decrypted "+decryptedText);

}
catch(Exception e)
{
e.printStackTrace();
}
return decryptedText;

}

}

最佳答案

您必须保留字节,而不是转换为字符串。

这篇文章的解释: Problems converting byte array to string and back to byte array

如果您想要保留字符串,请考虑转换为 B64

String my_string=DatatypeConverter.printBase64Binary(byte_array);

byte [] byteArray=DatatypeConverter.parseBase64Binary(my_string);

您还可以转换为十六进制(它更大)

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

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