Java AES 256加密 [英] Java AES 256 encryption
本文介绍了Java AES 256加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下java代码加密一个使用64个字符的字符串的字符串。我的问题是这是AES-256加密吗?
I have the below java code to encrypt a string which uses a 64 character key. My question is will this be a AES-256 encryption?
String keyString = "C0BAE23DF8B51807B3E17D21925FADF273A70181E1D81B8EDE6C76A5C1F1716E";
byte[] keyValue = hexStringToByte(keyString);
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.ENCRYPT_MODE, key);
String data = "Some data to encrypt";
byte[] encVal = c1.doFinal(data.getBytes());
String encryptedValue = Base64.encodeBase64String(encVal);
/* Copied the below code from another post in stackexchange */
public static byte[] hexStringToByte(String hexstr)
{
byte[] retVal = new BigInteger(hexstr, 16).toByteArray();
if (retVal[0] == 0)
{
byte[] newArray = new byte[retVal.length - 1];
System.arraycopy(retVal, 1, newArray, 0, newArray.length);
return newArray;
}
return retVal;
}
以下是纳入来自divanov和laz的建议后的代码。 >
The following is the code after incorporating suggestions from divanov and laz.
String keyString = "C0BAE23DF8B51807B3E17D21925FADF273A70181E1D81B8EDE6C76A5C1F1716E";
byte[] keyValue = DatatypeConverter.parseHexBinary(keyString);
Key key = new SecretKeySpec(keyValue, "AES");
Cipher c1 = Cipher.getInstance("AES");
c1.init(Cipher.ENCRYPT_MODE, key);
String data = "Some data to encrypt";
byte[] encVal = c1.doFinal(data.getBytes());
String encryptedValue = Base64.encodeBase64String(encVal);
推荐答案
是的,64个字符为32个字节256位和256位的任何序列都可以用作AES-256键。
Yes, it will as 64 characters are 32 bytes and 256 bits and any sequence of 256 bits can be used as an AES-256 key.
我建议您使用 DatatypeConverter.parseHexBinary (或类似的实用程序库您可以将十六进制字符串转换为字节数组。
I suggest you to use DatatypeConverter.parseHexBinary (or similar utility from library of your choice) to convert hexadecimal strings into byte arrays.
这篇关于Java AES 256加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文