Java encryption can be achieved in many different ways and methods and also with third party libraries and dependencies. This article will attempt to dive in a few of these areas, and will hopefully increase your knowledge of encryption with java.
The examples are all at our github repo. https://github.com/misterpki/java-encryption
Note that these examples are not production ready and should be analyzed by your security team before implementing them in your own code. Proceed with caution.
RSA encryption with Java
RSA is the most common asymmetric encryption algorithm. The Java Cipher class will be used in the following example to perform encryption on a String.
public static byte[] encryptRSA(final String plainText, final PublicKey publicKey) throws NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException {
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
cipher.update(plainText.getBytes());
return cipher.doFinal();
}
Notice that this method takes in a plain text String and a public key to encrypt with, and returns an encrypted Array of bytes.
The following transformations (algorithm/mode/padding) are supported with the Cipher class, along with their key sizes which are not to be included in the getInstance parameter.
AES/CBC/NoPadding (128)
AES/CBC/PKCS5Padding (128)
AES/ECB/NoPadding (128)
AES/ECB/PKCS5Padding (128)
AES/GCM/NoPadding (128)
DES/CBC/NoPadding (56)
DES/CBC/PKCS5Padding (56)
DES/ECB/NoPadding (56)
DES/ECB/PKCS5Padding (56)
DESede/CBC/NoPadding (168)
DESede/CBC/PKCS5Padding (168)
DESede/ECB/NoPadding (168)
DESede/ECB/PKCS5Padding (168)
RSA/ECB/PKCS1Padding (1024, 2048)
RSA/ECB/OAEPWithSHA-1AndMGF1Padding (1024, 2048)
RSA/ECB/OAEPWithSHA-256AndMGF1Padding (1024, 2048)
In English, the steps being performed for RSA encryption with Java are:
- Get a Cipher instance, specified in this case as “RSA/ECB/PKCS1Padding”.
- RSA is the encryption algorithm
- ECB (Electronic codebook) is the encryption mode.
- PKCS1Padding is the padding type.
- Initialize the cipher object with a purpose or mode, and the given public key.
- Update the cipher with the plain text to be encrypted.
- Perform the encryption with doFinal.
ECB (Electronic codebook) is not considered secure, but is being used purely for demonstration purposes.
RSA decryption with Java
The following is an example of how to RSA decrypt with Java.
public static String decryptRSA(final byte[] ciphertext, final PrivateKey privateKey)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
IllegalBlockSizeException
{
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(ciphertext));
}
- Create a Cipher object with the same padding as was done with the encryption.
- Initialize the cipher to decrypt mode with the private key being used for decryption. This should pair with the public key used for encryption.
- Return the decrypted String data.
AES encryption with Java
AES is arguably the most common symmetric key or secret key encryption algorithm. Two examples will be given for encrypting with the AES encryption algorithm, the first using AES CBS and the second using AES GCM.
public static byte[] encryptAESCBC(final String plainText, final SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
cipher.update(plainText.getBytes());
return cipher.doFinal();
}
The following steps are taken in the above example to perform AES encryption with CBC.
- Create a Cipher instance, specified in this case as “AES/CBC/PKCS5Padding”.
- AES is the encryption algorithm
- CBC is the encryption mode
- PKCS5Padding is the encryption padding.
- Initialize the Cipher object to perform encryption with a secret or symmetric key (also known as a shared key), in addition to an initialization vector.
- Update the Cipher object with the plain text to be encrypted.
- Perform the encryption with doFinal.
The following is an example of AES CBC decryption.
public static String decryptAESCBC(final byte[] ciphertext, final SecretKey secretKey)
throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
IllegalBlockSizeException, InvalidAlgorithmParameterException
{
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16]));
return new String(cipher.doFinal(ciphertext));
}
- Create a Cipher object using the same transformation as the encryption.
- Initialize the cipher to decrypt mode with the shared secret key and the same initialization vector used for encryption.
- Return the AES CBC decrypted String data.
This next example uses AES with GCM:
public static byte[] encryptAESGCM(final String plaintext, final SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * 8, new byte[16]);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
return cipher.doFinal(plaintext.getBytes());
}
The following steps are taken in the above example to perform AES encryption with GCM.
- Create a Cipher instance, specified in this case as “AES/GCM/NoPadding”.
- AES is the encryption algorithm
- GCM is the encryption mode
- NoPadding is used with GCM.
- Initialize the Cipher object to perform encryption with a secret or symmetric key (also known as a shared key), in addition to an initialization vector.
- Update the Cipher object with the plain text to be encrypted.
- Perform the encryption with doFinal.
This example performs AES GCM decryption with Java.
public static String decryptAESGCM(byte[] ciphertext, SecretKey secretKey) throws NoSuchPaddingException,
NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
IllegalBlockSizeException
{
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(16 * 8, new byte[16]);
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
byte[] decryptedText = cipher.doFinal(ciphertext);
return new String(decryptedText);
}
- Create a Cipher object with the same transformation used for encryption.
- Create a SecretKeySpec with the shared secret key and algorithm of that key.
- Create a GCMParameterSpec used for initialization of the Cipher object.
- Initialize the cipher to decrypt mode with the created secret key spec and GCM Parameter Spec.
- Perform the decryption and return the decrypted data as a String.
Java encryption Exceptions and Errors
The following Exceptions may be thrown by the above java encryption code examples:
NoSuchPaddingException if the padding given to getInstance is not a valid padding type.
InvalidKeyException if the key given to the init method is invalid or in the case of a required Initialization Vector parameter as in the AES encryption examples.
BadPaddingException if the padding mechanism is not expected on when performing the encryption on doFinal.
IllegalBlockSizeException if the length of the block size does not match the cipher.
NoSuchAlgorithmException if the algorithm given to getInstance is not a valid encryption algorithm.
Encryption Libraries
Listed below are encryption libraries that can take care of java encryption functions for you. If you would like to see examples of java encryption with any of these libraries please leave a comment and let us know.
Note that these examples are not intended to be used as production code but rather are to be used as a building block to learn about how to encrypt with Java.
Again, if you missed it at the beginning of the post, the examples are in our github repo: https://github.com/misterpki/java-encryption
Leave a Reply