Data Encryption
Another approach is to secure data using encryption. In order to perform encryption and decryption of information, a cipher algorithm and a key have to be selected. This key is then used to perform actual encryption and decryption actions, utilizing an appropriate cipher algorithm. The exact list of supported digest and encryption algorithms varies among different versions and implementations of Java, so developers should consult release-specific Java documentation for a full list of supported algorithms.
try {
String creditCard = “12345678890”;
SecretKey key = KeyGenerator.getInstance(“AES”).generateKey(); // (1)
Cipher cipher = Cipher.getInstance(“AES/GCM/NoPadding”); // (2)
cipher.init(Cipher.ENCRYPT_MODE, key); // (3)
byte[] encryptedValue = cipher.doFinal(creditCard.getBytes()); // (4)
GCMParameterSpec ps = cipher.getParameters()
.getParameterSpec(GCMParameterSpec.class);
cipher.init(Cipher.DECRYPT_MODE, key, ps); // (5)
byte[] decryptedValue = cipher.doFinal(encryptedValue); // (6)
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
The numbered comments below correspond to the numbered lines in the code:
- The key in this example is generated on the fly using the AES algorithm. However, often keys are created in advance and stored in secure SSL wallet files that implement password-protected key storage.
- A new javax.crypto.Cipher object is created that is associated with a cipher algorithm.
- A cipher is now associated with a key and initialized to be used for encryption.
- A value is encrypted using the previously initialized cypher. There are several methods provided by the Cipher class that can perform the encryption or decryption, such as update() and doFinal(). In simple cases, a single doFinal() method call can be used to perform encryption or decryption actions. In more complex scenarios, such as the need to handle large messages, multiple-part encryption or decryption mechanics can be used with intermediate actions performed by the update() method, before the invocation of the doFinal() method.
- Next, a cipher parameter specification object is acquired, which is used to set up the cipher for the decryption mode. Notice that the same key that was used for encrypting the values is now used to decrypt them.
- Finally, the cipher is used to decrypt the values.
Notice that the cipher encrypts and decrypts values as byte arrays, so any other type values should first be converted into a byte array before encryption can happen. After decryption completes, the byte array containing the decrypted value can be converted to the required type.
Finally, when exchanging information among different systems, consider only transmitting the minimal amount of data outside an application, if possible.