Created
June 18, 2013 04:21
-
-
Save 4noha/5802658 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # -*- coding: utf-8 -*- | |
| require 'openssl' | |
| require 'base64' | |
| #require 'pack' | |
| class CryptUtil | |
| def self.encrypt(pass, value) | |
| enc = OpenSSL::Cipher.new('aes-128-cbc') | |
| # 暗号化or復号化どちらを行うかセット(今回は暗号化)、復号化の場合はdecrypt | |
| enc.encrypt | |
| # ivを生成 | |
| #iv = OpenSSL::Random.random_bytes(16) | |
| iv = "0123456789abcdef" #今回ivは固定 | |
| # 暗号化する際のキー文字列をセット | |
| enc.key = pass | |
| # ivをセット | |
| enc.iv = iv | |
| crypted = "" | |
| crypted << enc.update(value) # 暗号化 | |
| crypted << enc.final | |
| # 暗号化した文字列と暗号化に使用したivをBase64エンコードして返却 | |
| return [crypted].pack('m0'), [iv].pack('m0') #0の有無は改行なしの有無 | |
| end | |
| def self.decrypt(pass, encrypted, iv) | |
| dec = OpenSSL::Cipher.new('aes-128-cbc') | |
| # 暗号化する際のキー文字列をセット | |
| dec.key = pass | |
| # Base64エンコードされたivをデコードしてセット | |
| dec.iv = iv.unpack('m')[0] unless iv.nil? | |
| dec.decrypt | |
| plain_text = "" | |
| plain_text << dec.update(encrypted.unpack('m')[0]) | |
| plain_text << dec.final | |
| return plain_text | |
| end | |
| end | |
| text = "日本語" | |
| text64_and_iv64 = CryptUtil.encrypt("aaaaaaaaaaaaaaaa", text) | |
| puts text64_and_iv64[0] | |
| puts CryptUtil.decrypt("aaaaaaaaaaaaaaaa", a, text64_and_iv64[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment