2
2

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.

RubyでAWS KMS (Key Management Service)を使ってみる

Last updated at Posted at 2014-11-19

Class: Aws::KMS::Client - AWS SKD for Ruby V2を参考に使ってみた。

基本形

require 'aws-sdk-core'

kms = Aws::KMS::Client.new

# 暗号
resp = kms.encrypt(
  key_id: 'be8a4c03-4816-48ba-a3c9-xxxxxxxx', # ↓arnでも可
  # key_id: 'arn:aws:kms:ap-northeast-1:1234567890:key/be8a4c03-4816-48ba-a3c9-xxxxxxxx',
  plaintext: 'ここに暗号化したい文字列など') 

# 復号
puts kms.decrypt(ciphertext_blob: resp.ciphertext_blob).plaintext

補足) key_idにalias(鍵の名前)は使えませんでした。 (2014/11/19)

Authenticated Encryption

require 'aws-sdk-core'

kms = Aws::KMS::Client.new

# 暗号
resp = kms.encrypt(
  key_id: 'be8a4c03-4816-48ba-a3c9-xxxxxxxx',
  plaintext: 'ここに暗号化したい文字列など',
  encryption_context: { EncryptionContextKey: '秘密のパスワード(はーと)' }) 

# 復号
puts kms.decrypt(
  ciphertext_blob: resp.ciphertext_blob,
  encryption_context: { EncryptionContextKey: '秘密のパスワード(はーと)' }
).plaintext

復号時に指定したEncryptionContextKeyが正しくない場合例外が投げられました。

さいごに

可逆暗号がこんなに簡単にできる。すごい。
バイナリを暗号化したい場合はBase64エンコードでもすればいいですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?