Decrypt Data
To decrypt data:
Create an
NAESession
object. Pass the NAE username and password as arguments.Specify the IV used to encrypt the text string by creating a byte array.
Store the existing ciphertext in a byte array.
Get an instance of a Cipher object. Pass the algorithm, mode, and padding as arguments.
Obtain an instance of the key you want to use for the decryption operation.
Initialize the Cipher object to decrypt mode. If necessary, create a new
IvParameterSpec
object and set it to the value contained in the IV byte array.Invoke the
doFinal
method of the Cipher object to perform the decryption and store the plaintext in a byte array.
Code sample
The example below decrypts a string with the key user1key. This decryption operation uses the AES algorithm in CBC mode with PKCS5 padding - the same values used to encrypt the string. When using AES in CBC mode, you must supply a 16 byte initialization vector (IV). This must be the same IV used to encrypt the string.
NAESession session = NAESession.getSession("user1","password1".toCharArray());
byte [] iv = ...
/* get IV used during Encrypt operation */
byte [] ciphertext = ...
/* get ciphertext */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","IngrianProvider");
SecretKey key = NAEKey.getSecretKey("user1key", session);
cipher.init(Cipher.DECRYPT_MODE, key,newIvParameterSpec(iv));
byte [] plaintext = cipher.doFinal(ciphertext);
String hello =new String(plaintext);