0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

KMS) エンベロープ暗号化でopensslで暗号化してjavaで復号化する

Last updated at Posted at 2019-08-28

備忘録です

セキュリティあんまり強くないので、こんなやり方もあるよくらいの参考でお願いします

AWS CLIで KMS DataKeyを生成する

$ aws kms generate-data-key --key-spec "AES_128" --key-id "arn:aws:kms:REGION_NAME:ACCOUNT_ID:key/HOGEHOGE"

{
  "ciphertextBlob": "foo",
  "Plaintext" : "bar",
  "KeyId" : "KEY-ID"
}

返却される ciphertextBlog, PlaintextはBase64-encodedされています

Opensslで暗号化する

$ KEY=$(echo "bar" | base64 -d | od -A n -t x1 -v | sed -e 's/ //g')
$ openssl aes-128-ecb -e -in secret.txt -out encrypted.txt -base64  -K ${KEY}

KEY = KMSのDataKey を HEX文字列に変えたもの(求:もっとスマートな方法
openssl コマンドで暗号化。このとき初期化ベクトル不要なブロック処理にしています

Javaで復号化する

String encryptedTxt = "baz";
String plainDataKey = "bar";

byte[] key = DatatypeConverter.parseBase64Binary(plainDataKey);

SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);

byte[] encrypted = DatatypeConverter.parseBase64Binary(encryptedTxt);

String decryptedTxt = new String(cipher.doFinal(encrypted));
System.out.println("result: " + decryptedTxt);

上記の例では、plainDataKey ベタ書きしてますけど、
正しくは plainDataKeyは、AWSのドキュメントを参考にciphertextBlogをデコードして取得してください。
あと、使い終わったplainDataKeyは早々に削除するようにAWSドキュメントにも記載があります。

その他

ちゃんとするなら、鍵と初期化ベクトルを生成したほうがいいです。
楽した = セキュリティの低下 と思ってください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?