廢話不多,先自己看一下kms的相關文章:
https://aws.amazon.com/tw/kms/
解決上述問題的實作,可以參考:
https://java.awsblog.com/post/TxRE9V31UFN860/Secure-Local-Development-with-the-ProfileCredentialsProvider
http://docs.aws.amazon.com/kms/latest/developerguide/programming-encryption.html
這邊卡關了一下子,因為一直想把ciphertext bytebuffer 用 new String(bytes, charset)方式轉成字串,得到的結果就是一些看不懂的亂碼。
解決辦法就是在轉字串前,先將加密的byte buffer用base64 encode過後,再轉成一般字串;解密時當然就是再用base64 decode再wrap成byte buffer就可以拉。範例程式碼如下:
public String encrypt(String plainInput) {
ByteBuffer plaintext = ByteBuffer.wrap(plainInput.getBytes(StandardCharsets.US_ASCII));
EncryptRequest req = new EncryptRequest().withKeyId(keyId).withPlaintext(plaintext);
ByteBuffer ciphertext = kms.encrypt(req).getCiphertextBlob();
return new String(new Base64().encode(ciphertext.array()));
}
public String decrypt(String cipherInput) {
ByteBuffer ciphertextBlob = ByteBuffer.wrap(new Base64().decode(cipherInput));
DecryptRequest req = new DecryptRequest().withCiphertextBlob(ciphertextBlob);
ByteBuffer plainText = kms.decrypt(req).getPlaintext();
return new String(plainText.array(), StandardCharsets.US_ASCII);
}