class Des
require 'openssl'
require 'base64'
ALG = 'DES-EDE3-CBC'
KEY = "mZ4Wjs6L"
DES_KEY = "nZ4wJs6L"
#加密
def encode(str)
des = OpenSSL::Cipher::Cipher.new(ALG)
des.pkcs5_keyivgen(KEY, DES_KEY)
des.encrypt
cipher = des.update(str)
cipher << des.final
return Base64.encode64(cipher) #Base64编码,才能保存到数据库
end
#解密
def decode(str)
str = Base64.decode64(str)
des = OpenSSL::Cipher::Cipher.new(ALG)
des.pkcs5_keyivgen(KEY, DES_KEY)
des.decrypt
des.update(str) + des.final
end
end
require 'pp'
des = Des.new
str = '1234567890123456'
pp '=====encrypt====='
str = des.encode(str)
pp str
pp '=====decrypt====='
pp des.decode(str)