Java AES 256 encryption

和自甴很熟 提交于 2019-12-30 05:34:05

问题


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

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

回答1:


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.

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



来源:https://stackoverflow.com/questions/21518678/java-aes-256-encryption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!