Encrypt String and Write to File
To encrypt a string and write result to a file:
Create an
NAESession
object. Pass the NAE username and password as arguments.If required, specify an IV by creating a new 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 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.Create and open a file where the encrypted data will be written.
Specify that the Cipher object is used to write to the file.
Invoke
getBytes
to write the plaintext to theCipherOutputStream
.Close the cipher stream.
Code sample
NAESession session = NAESession.getSession("user1","password1".toCharArray());
byte [] iv = ... /* set IV byte array to 16 byte value of the IV */
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","IngrianProvider");
SecretKey key = NAEKey.getSecretKey("user1key", session);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
OutputStream fos = new FileOutputStream("hello.enc");
OutputStream cos = new CipherOutputStream(fos, cipher);
cos.write("Hello World!".getBytes());
cos.close();
fos.close();