Cipher

Using the Cipher service.

The Cipher provider only supports the AES/CTR/NoPadding algorithm. Keys generated with the KeyGenerator are always 128 bit keys.

An example of encrypting and decrypting with the Cipher follows:

//Generate AES key
final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES", SepiorProvider.PROVIDER_NAME);
final Key key = keyGenerator.generateKey();

//Setup IV parameter
final SecureRandom secureRandom = new SecureRandom();
final byte[] nonce = new byte[96 / 8];
secureRandom.nextBytes(nonce);
final byte[] iv = new byte[128 / 8];
System.arraycopy(nonce, 0, iv, 0, nonce.length);
final IvParameterSpec ivSpec = new IvParameterSpec(iv);

final String data1 = "encrypt this part first";
final String data2 = "continue with this";

//Setup Cipher
final Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", SepiorProvider.PROVIDER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

//Encrypt
final byte[] part1 = cipher.update(data1.getBytes());
final byte[] part2 = cipher.doFinal(data2.getBytes());
final ByteBuffer buffer = ByteBuffer.allocate(part1.length + part2.length);
buffer.put(part1);
buffer.put(part2);

//Decrypt
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
final byte[] pt = cipher.doFinal(buffer.array());