Java AES 256 加密

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21518678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:06:55  来源:igfitidea点击:

Java AES 256 encryption

javaaesencryption

提问by rupen

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?

我有以下 java 代码来加密使用 64 个字符的密钥的字符串。我的问题是这会是 AES-256 加密吗?

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;
}

The following is the code after incorporating suggestions from divanov and laz.

以下是合并了 divanov 和 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);

采纳答案by divanov

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.

是的,因为 64 个字符是 32 字节和 256 位,任何 256 位序列都可以用作 AES-256 密钥。

I suggest you to use DatatypeConverter.parseHexBinary(or similar utility from library of your choice) to convert hexadecimal strings into byte arrays.

我建议您使用DatatypeConverter.parseHexBinary(或您选择的库中的类似实用程序)将十六进制字符串转换为字节数组。