Encrypt Data
To encrypt data:
Create an
NAESession
object. Pass the NAE username and password as arguments.Create an
NAESecureRandom
object. Pass the NAESession object as an argument.If required, specify an IV by creating a new byte array.
Get an instance of a Cipher object. Pass the algorithm, mode, and padding scheme as arguments.
Obtain an instance of the key you want to use for the encryption operation.
Initialize the Cipher object to encrypt mode. If necessary, create a new
IvParameterSpec
object and set it to the value contained in the IV byte array.Convert the plaintext to a byte array and invoke the
doFinal
method of the Cipher object to perform the encryption.
Code sample
The sample here encrypts the text string Hello World with the key user1key. This encryption operation uses the AES algorithm in CBC mode with PKCS5 padding. When using AES in CBC mode, you must supply a 16 byte initialization vector (IV).
NAESession session = NAESession.getSession("user1","password1".toCharArray());
NAESecureRandom sr=new NAESecureRandom(session);
byte []iv = new byte[16];
sr.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","IngrianProvider");
SecretKey key = NAEKey.getSecretKey("user1key", session);
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(iv));
byte [] ciphertext = cipher.doFinal("Hello World!".getBytes());
Tip
Save the IV, you can't decrypt your data without the random IV.
To decrypt the ciphertext, refer to Decrypt text string.