In your code snippet, raw
is your key (as a byte array):
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// ^^^ this is your key
Of course, if you have your key as a hex string, you'll need to convert it to bytes.
When encrypting, you can either specify an IV yourself or let a random one be generated. If you want to specify yourself, use:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // adjust padding
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(...));
if you want to use an automatic one, be sure to record which one was chosen by calling
cipher.getIV();
For decryption, you must specify the IV and you do so using an IvParameterSpec
, just like with encryption.
And I need to decrypt only first 256 bytes data only. How can I achieve this?
Consider using a CipherInputStream
and read only 256 bytes from it.