2

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);
3
  • possible duplicate of Java 256-bit AES Password-Based Encryption Commented Feb 3, 2014 at 3:57
  • 1
    That question seems to ask about PBE derivation of AES key. Commented Feb 3, 2014 at 5:31
  • Where is that post that performs the incorrect hex decoding? I desperately need to downvote it. Commented Feb 3, 2014 at 20:11

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Really? Did you see byte[] new = new byte[retVal.length - 1];?
This is a clumsy attempt to deal with sign byte appended by BigInteger.
There is DatatypeConverter that is part of the main Java API for decoding the hex string as well: docs.oracle.com/javase/7/docs/api/javax/xml/bind/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.