13
7

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.

AWS Lambdaで使う秘密情報をKMSを使って渡す (with Node.js)

13
Last updated at Posted at 2016-04-28

概要

KMS(AWS Key Management Service)を使うと、コードに直書きできない情報を安全に AWS Lambdaに渡せる
普通は環境変数を使うのが一般的だが、現在Lambdaには環境変数を設定できないのでこのような代替案が必要になる
ここでは、KMSを使った暗号化、復号化の方法を簡単に説明する

KMSを使うことの主なメリットは、

  1. KMS, LambdaともにAWSのサービスなので、親和性が高い
  2. 暗号化の際におきる、鍵の保管場所という厄介な問題を回避できる
    の2点
    実行環境はNode.jsとする

encrypt

コマンドライン上でencryptしてコードに書きこむ

  1. AWS CLIをインストール
  2. AWSのconsole上で、新たなmaster keyを作成する
    • 現状ではKMS用のアイコンはなく、Identity and Access Managementからいくので注意
  3. master keyを作成した地域を指定して、目的の文字列を暗号化する (下は東京リージョンの場合)
    $ aws kms encrypt --key-id alias/some_key_name --region ap-northeast-1 --plaintext "password1"
  4. 出力結果のCiphertextBlobをpasswordとして格納する

注意点

  • 3の出力値は下記形式
  • データはbase64フォーマットされている
{ 
  "KeyId": "****",
  "CiphertextBlob": "****"
}

decrypt

実行時にAWS経由でdecryptする

注意点:

  • Promiseはbluebirdで上書きしているので注意
  • ES2015組み込みのPromiseを使う場合は、kms.decryptをラップすること
import Promise from 'bluebird'
import AWS     from 'aws-sdk'

const kms = new AWS.KMS({ region: 'hogehoge' });
const decryptAsync = Promise.promisify(kms.decrypt, { context: kms })
const decodedPromise = (encrypted) => {
  const encryptedBuf = new Buffer(encrypted, 'base64');
  const cipherText = { CiphertextBlob: encryptedBuf }
  return decryptAsync(cipherText).then(data => data.Plaintext.toString('utf8'))
}

参考

AWS Key Management Service
10分でわかる!Key Management Serviceの仕組み #cmdevio

13
7
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
13
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?