Encrypting a byte [ ] using a AES 256 Session key

1.4k Views Asked by At

I have a Session key which is Changing with every execution of the program. I have to encrypt a byte[ ] using that session key (AES 256) so how to do that.

I am generating my key by

              Key key;
              SecureRandom rand = new SecureRandom();
              KeyGenerator generator = KeyGenerator.getInstance("AES");
              generator.init(rand);
              generator.init(256);
              key = generator.generateKey();

And using this to Encrypt the Byte Array

 public static byte[] Encrypt(byte[] a,Key skey) throws Exception {

 // Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");  
cipher.init(Cipher.ENCRYPT_MODE, skey);

byte[] encrypted =cipher.doFinal(a);
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);

return encrypted;
}

But Every time i run the program it shows and error

       Exception in thread "main" java.security.InvalidKeyException: Illegal          
     key size or default parameters
         at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1026)
            at javax.crypto.Cipher.implInit(Cipher.java:801)
    at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
    at javax.crypto.Cipher.init(Cipher.java:1249)
    at javax.crypto.Cipher.init(Cipher.java:1186)
    at com.esign.verify.DocHash.AES.Encrypt(AES.java:52)
    at com.esign.verify.DocHash.DocHash.main(DocHash.java:264)
0

There are 0 best solutions below