Encrypt File
To encrypt a file:
Create an
NAESession
object. Pass the NAE username and password as arguments.Set the IV.
Get an instance of the cipher object, pass the algorithm, mode, and padding as arguments.
Obtain an instance of the key you want to use for the encryption operation. The example below uses user1key.
Initialize the Cipher object to encrypt mode.
Create a new buffer of 2048 bytes and declare the ciphertext byte array, which is used later.
Create an input stream for the file.
Create an output stream for the file.
Declare a
len
variable. This variable will record how many bytes have been read at a time.Create a loop that reads data from the input file and stores it in the buffer.
Pass the buffer to the update method of the cipher object. This is where the actual encryption is done. The file is read 2048 bytes at a time. If the file is not a multiple of 2048 bytes, the read method will read some value less than 2048 on its last pass. The rest of the last pass is garbage - left overs from the previous read operation. The
len
variable tells the update method how many total bytes to use and, therefore, how much of the last pass to ignore.
Some block algorithms require a certain number of bytes to perform an encryption operation else, cipher.update
might return null.
Check that
cipher.update
has not returned a null value.Call the
doFinal
method and write the encrypted text to the output file.Close the input and output files.
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));
byte[] readBuffer = new byte[2048];
byte[] ciphertext;
InputStream fis = new FileInputStream("myfile");
OutputStream fos = new FileOutputStream("myfile.enc");
int len;
while ((len = fis.read(readBuffer)) != -1)
{
ciphertext = cipher.update(readBuffer, 0, len);
if (ciphertext != null) {
fos.write(ciphertext);
}}
ciphertext = cipher.doFinal();
if (ciphertext != null) {
fos.write(ciphertext);
}
fis.close();
fos.close();