0

I am facing exception for below code while doing encryption. Created key is "[B@29ee9faa". "Error while encrypting: java.security.InvalidKeyException: Invalid AES key length: 11 bytes"

Also i have already updated my local_policy and Us_export_policy in my jre/lib/security.

  public static String generateKey(String eisId) 
  {
    String uuidKey = null;
    try {

        KeyGenerator gen = KeyGenerator.getInstance("AES");
        gen.init(128); /* 128-bit AES */
        SecretKey secret = gen.generateKey();
        uuidKey = secret.getEncoded().toString();
        System.out.println("uuidKey : "+uuidKey);

        // Store in DB
        // **********************

    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return uuidKey;
}

public static SealedObject encryptData(String eisId, SecurityDomainDTO sDObj) 
{
    try
    {
        String secret = generateKey(eisId);
        SecretKeySpec aesKey = new SecretKeySpec(secret.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        SealedObject so = new SealedObject(sDObj, cipher);

        return so;
    } 
    catch (Exception e) 
    {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}

1 Answers1

0

The "[B@29ee9faa" string is a big clue. That's what you will get when you call toString() on a byte[]. It does NOT represent the contents of the byte array. Rather, it represnts the internal type name ("[B") and the object's identity hashcode.

This is the error:

      uuidKey = secret.getEncoded().toString();

That is not the correct way to format the contents of a byte array.

I suggest that you use the Base64 class; e.g.

    Base64.Encoder encoder = Base64.getEncoder();
    String encoded = encoder.encode(bytes);

    ...

    Base64.Decoder decoder = Base64.getDecoder();
    byte[] bytes = decoder.decode(encoded);
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216