stackoverflow
stackoverflow

Reputation: 19474

How to turn 64 character string into key for 256 AES encryption

public static byte[] decryptByte(byte[] blahh, byte[] keyExample) throws Exception
{
Cipher cipher = null;

try
{
    cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    return cipher.doFinal(Base64.decodeBase64(blah));
}
catch(Exception e)
{
    e.printStackTrace();
}
return null;
}

String keyExample = "99112277445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";
byte[] key = keyExample.getBytes();    
byte[] barrayMessage = {123,45,55,23,64,21,65};    
byte[] result = decryptByte(barrayMessage, key);

Exception thrown: java.security.InvalidKeyException: Invalid AES key length: 64 bytes

Upvotes: 1

Views: 7902

Answers (2)

Tom
Tom

Reputation: 26839

When you call String.getBytes() (JDK documentation) you encodes characters of the given string into a sequence of bytes using the platform's default charset.

What you are actually need to do is to convert each hexadecimal (also base 16) number (represented by two characters from 0 to 9 and A to F e.g. 1A, 99, etc.) into its corresponding numerical (byte) value e.g. "FF" -> -1 byte.

Sample code is as follows:

import static java.lang.Character.digit;
...

private static byte[] stringToBytes(String input) {
    int length = input.length();
    byte[] output = new byte[length / 2];

    for (int i = 0; i < length; i += 2) {
        output[i / 2] = (byte) ((digit(input.charAt(i), 16) << 4) | digit(input.charAt(i+1), 16));
    }
    return output;
}

...

String keyExample = "99112277445566778899AABBCCDDEEFF0123456789ABCDEF0123456789ABCDEF";
byte[] key = stringToBytes(keyExample);    
byte[] barrayMessage = {123,45,55,23,64,21,65};    
byte[] result = decryptByte(barrayMessage, key);

Please bear in mind that because we convert each two characters into a single byte, the proposed method assumes your input will have even number of characters (also the input is not null and empty).

If that method is going to be used internally that form is acceptable but if you make it as a part of library visible to others, it would be good to put some checks and throw exception on invalid input.

Upvotes: 3

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

You should try and decode your key using a hexadecimal decoder instead of calling getBytes().

Upvotes: 3

Related Questions