Created
November 9, 2014 07:44
-
-
Save suzuki-kei/0c4815e941c59ebe6c65 to your computer and use it in GitHub Desktop.
Ruby で暗号化するサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
class Cipher | |
# 初期化ベクトル. | |
attr_reader :iv | |
# 暗号鍵. | |
attr_reader :key | |
# 暗号アルゴリズム. | |
attr_reader :algorithm | |
# | |
# 利用可能なアルゴリズムを取得する. | |
# | |
# ==== 戻り値 | |
# 利用可能なアルゴリズムを含む配列. | |
# | |
def self.algorithms | |
OpenSSL::Cipher::Cipher.ciphers.map(&:upcase).sort.uniq | |
end | |
# | |
# インスタンスを初期化する. | |
# | |
# ==== 引数 | |
# algorithm: アルゴリズム. | |
# iv: 初期化ベクトル. | |
# key: 暗号鍵. | |
# | |
def initialize(algorithm, key: nil, iv: nil) | |
@algorithm = algorithm | |
@key = key | |
@iv = iv | |
end | |
# | |
# ランダムな初期化ベクトルを生成する. | |
# | |
# ==== 戻り値 | |
# ランダムに生成した初期化ベクトル. | |
# | |
def generate_iv! | |
@iv = OpenSSL::Cipher::Cipher.new(algorithm).random_iv | |
end | |
# | |
# ランダムな暗号鍵を生成する. | |
# | |
# ==== 戻り値 | |
# ランダムに生成した暗号鍵. | |
# | |
def generate_key! | |
@key = OpenSSL::Cipher::Cipher.new(algorithm).random_key | |
end | |
# | |
# 暗号化する. | |
# | |
# ==== 引数 | |
# plain_text:: 暗号化対象の平文. | |
# | |
# ==== 戻り値 | |
# plain_text を暗号化した値. | |
# | |
def encrypt(plain_text) | |
process(:encrypt, plain_text) | |
end | |
# | |
# 復号する. | |
# | |
# ==== 引数 | |
# cipher_text:: 復号対象の暗号文. | |
# | |
# ==== 戻り値 | |
# cipher_text を復号した値. | |
# | |
def decrypt(cipher_text) | |
process(:decrypt, cipher_text) | |
end | |
private | |
# | |
# 暗号化または復号を行う. | |
# | |
# ==== 引数 | |
# mode:: 暗号化する場合は :encrypt, 復号する場合は :decrypt を指定する. | |
# value:: 暗号化または復号対象の値. | |
# | |
# ==== 戻り値 | |
# value を暗号化または復号した値. | |
# | |
def process(mode, value) | |
cipher = OpenSSL::Cipher::Cipher.new(algorithm).send(mode) | |
cipher.key, cipher.iv = key, iv | |
cipher.update(value) + cipher.final | |
end | |
end | |
def encode(value) | |
value.unpack('H*').first | |
end | |
def decode(value) | |
[value].pack('H*') | |
end | |
if $0 == __FILE__ | |
cipher = Cipher.new('AES-256-CBC') | |
cipher.generate_iv! | |
cipher.generate_key! | |
puts "iv : #{encode(cipher.iv)}" | |
puts "key : #{encode(cipher.key)}" | |
plain_text = '秘密の文字列' | |
puts "plain text : #{plain_text}" | |
encrypted = cipher.encrypt(plain_text) | |
puts "cipher text : #{encode(encrypted)}" | |
decrypted = cipher.decrypt(encrypted) | |
puts "plain text : #{decrypted}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment