KMSは難しい。というか、もうあらゆる事が僕にとっては、とても難しい。 boto3を用いてKMSを用いたシンプルな暗号化と復号化の方法を確認する。
Pythonとboto3を使って暗号化と復号化を確認する
import base64
import boto3
key_arn = "arn:aws:kms:REGION:111111111111:key/KEY_ID"
kms = boto3.client('kms')
enc_resp = kms.encrypt(KeyId=key_arn, Plaintext="yay") # 暗号化
cipher_data: bytes = enc_resp['CiphertextBlob'] # 暗号文
cipher_text = base64.b64encode(cipher_text).decode('utf-8')
dec_resp = kms.decrypt(CiphertextBlob=cipher_data) # 復号化
plain_data: bytes = dec_resp["Plaintext"]
plain_data.decode()
GoとAWS SDK for Goを使って暗号化と復号化を確認する
package main
import (
"fmt"
"encoding/base64"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
)
func main() {
var (
profile = "DUMMY"
key_arn = "arn:aws:kms:REGION:ACCOUNT_ID:keyKEY-ID"
)
c := aws.NewConfig()
o := session.Options{
Config: *c,
Profile: profile,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
SharedConfigState: session.SharedConfigEnable,
}
s := session.Must(session.NewSessionWithOptions(o))
kmsSvc := kms.New(s)
encInput := kms.EncryptInput{
KeyId: aws.String(key_arn),
Plaintext: []byte("yay"), // message
}
r, err := kmsSvc.Encrypt(&encInput)
if err != nil {
panic(err)
}
ciphert := base64.StdEncoding.EncodeToString(r.CiphertextBlob)
fmt.Println(ciphert)
// fmt.Println(r.CiphertextBlob) // []byte
cipherb, err := base64.StdEncoding.DecodeString(ciphert)
if err != nil {
panic("error converting string to blob, " + err.Error())
}
decInput := kms.DecryptInput{
CiphertextBlob: cipherb,
}
rd, err := kmsSvc.Decrypt(&decInput)
if err != nil {
panic(err)
}
t := string(rd.Plaintext)
fmt.Println(t)
}