#RSA公钥加密,加签;des 不同加密算法的加密解密方法
require 'base64'
require 'digest'
#一 rsa加签 base64编码
def rsa_sign data, key
rkey =OpenSSL::PKey::RSA.new key
sign= rkey.sign('sha1',data)
signature = Base64.encode64(sign)
signature.gsub!("\n",'')
end
#二 rsa加密 并编码
def rsa_encrypt(public_key,data)
rsa= OpenSSL::PKey::RSA.new(Base64.decode64(public_key)) #是否需要decode依赖传的数据
#rsa=OpenSSL::Pkey::RSA.new(File.read('./public_key.pem'))
rsa_data = rsa.public_encrypt(data)
result =Base64.encode64(rsa_data)
result.gsub!("\n",'')
end
#HSA加密方法整理
def digest_sha?(data,type)
case type
when 1
Digest::SHA1.hexdigest(data)
when 256
Digest::SHA256.hexdigest(data)
when 384
Digest::SHA384.hexdigest(data)
when 512
Digest::SHA512.hexdigest(data)
end
end
ALG='DES-EDE3' # OpenSSL::Cipher::Cipher.ciphers : 可以获取ruby中所有支持的加解密
def des3_encrypt(des_key, des_text)
des =OpenSSL::Cipher::Cipher.new(ALG)
des.encrypt
des.key=des_key
result = des.update(des_text)
result << des.final
data=Base64.encode64(result)
data.gsub!("\n",'')
end
def des3_decrypt(des_key,des_text)
des =OpenSSL::Cipher::Cipher.new(ALG)
des.decrypt
des.padding=7 # set pckspadding1--7
des.key=des_key
text = Base64.decode64(des_text)
result = des.update(text).gsub(/\t|\b|\n/,'')
result << des.final
result
end
require 'digest/md5'
#MD5加密
Digest::MD5.hexdigest(data)