Araz Jafaripur
Araz Jafaripur

Reputation: 906

AES encryption error in java

i try to decrypt a encrypted text and use this code but get this error to me:

Exception in thread "main" java.security.InvalidKeyException: Illegal key size

and decryption code is:

String key = "ffce885876a617e7";
    String vector = "9ee153a3df56965e7baf13a7fa1075cc";


    IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
    SecretKeySpec keySpec = new SecretKeySpec(vector.getBytes(), "AES");


    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); //error occured in this line

Upvotes: 0

Views: 698

Answers (2)

Araz Jafaripur
Araz Jafaripur

Reputation: 906

I uses this one to decrypt AES. But in Android env instead of Java vanila.

public String decrypt(String enc) throws Exception {
    try {
        String key = "ffce885876a617e7";
        String vector = "9ee153a3df56965e7baf13a7fa1075cc";

        IvParameterSpec ivSpec = new IvParameterSpec(key.getBytes());
        SecretKeySpec keySpec = new SecretKeySpec(vector.getBytes(),
                "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        return new String(cipher.doFinal(hexToByte(enc)), "UTF-8");

    } catch (Exception localException) {
        throw new Exception("[decrypt] " + localException.getMessage());
    }
}

private static byte[] hexToByte(String enc) {
    int j = enc.length() / 2;
    byte[] arrayOfByte = new byte[j];

    if (j >= 2) {
        for (int i = 0; i < j; i++) {
            arrayOfByte[i] = ((byte) Integer.parseInt(
                    enc.substring(i * 2, 2 + i * 2), 16));
        }
    }
    return arrayOfByte;
}

Upvotes: 0

fge
fge

Reputation: 121710

.getBytes() will not automagically convert a "hex string" to the matching bytes.

Instead, try this utility method:

private static byte[] hexStringToBytes(final String input)
{
    final int len = input.length();
    if (len % 2 != 0)
        throw new IllegalArgumentException();

    final byte[] ret = new byte[len / 2];
    int offset = 0;

    for (int i = 0; i < ret.length; i++) {
        ret[i] = (byte) Integer.parseInt(input.substring(offset, offset+2), 16);
        offset += 2;
    }

    return ret;
}

Then in your code use hexStringToBytes(key) etc.

Upvotes: 1

Related Questions