Using the KMS key

In the previous step, we created a master key; now we will use this key to encrypt and decrypt data in the application. The use case is in the properties file. The database password needs to be kept in encrypted format.

The following is a Java class used to encrypt and decrypt the data using KMS. Use this class to first encrypt the data and then use the encrypted string in the properties file. Replace the keyId in the following code with the ARN of the key you created in the previous section. The ARN of the key can be viewed by double-clicking on the key you want to use from the Encryption Keys screen from the IAM dashboard. Remove the credentials if you are running it within the EC2 instance:

public class KMSClient{
private String keyId = "arn:aws:kms:us-west-2:450394462648:key/1cd0e2d5-61e1-4a71-a6b2-b9db825c9fce";
private AWSCredentials credentials;
private AWSKMSClient kms;

public KMSClient(){
credentials = new BasicAWSCredentials(accessKey, secretKey);

kms = new AWSKMSClient(credentials);
kms.setEndpoint("kms.us-west-2.amazonaws.com");
}

public String encryptData(String plainText) {
ByteBuffer plaintext = ByteBuffer.wrap(plainText.getBytes());
EncryptRequest req = new EncryptRequest().withKeyId(keyId).withPlaintext(plaintext);
ByteBuffer ciphertext = kms.encrypt(req).getCiphertextBlob();
String base64CipherText = "";
if (ciphertext.hasArray()){
base64CipherText=Base64.encodeAsString(ciphertext.array());
}
return base64CipherText;
}

public String decryptData(String cipherText) {
ByteBuffer cipherTextBlob = null;
cipherTextBlob = ByteBuffer.wrap(Base64.decode(cipherText));
DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherTextBlob);
ByteBuffer plainText = kms.decrypt(req).getPlaintext();
String plainTextString = new String( plainText.array(), java.nio.charset.StandardCharsets.UTF_8 );
return plainTextString;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.3.136