1. DES 加密
require "openssl"
class EncryptDes
def initialize(_key = "", _iv = "")
@encrypt = OpenSSL::Cipher::Cipher.new("DES-CBC")
_key.size < 8 ? @encrypt.random_key : (@encrypt.key = _key)
_iv.size < 8 ? @encrypt.random_iv : (@encrypt.iv = _iv)
end
# DES 加密
def encrypt(text)
@encrypt.encrypt
ret = @encrypt.update(text)
ret << @encrypt.final
end
# DES 解密
def decrypt(encrypt_value)
@encrypt.decrypt
ret = @encrypt.update(encrypt_value)
ret << @encrypt.final
end
end
2. RSA 加密
require "openssl"
class EncryptRsa
def initialize(num = 1024)
num = 1024 if num < 32
rsa = OpenSSL::PKey::RSA.new(num)
@public_key = rsa.public_key.to_pem
@private_key = rsa.to_pem
end
# 私密加密
def private_encrypt(value)
rsa_private_encrypt(value, @private_key)
end
# 私密解密
def private_decrypt(value)
rsa_public_decrypt(value, @public_key)
end
# 公密加密
def public_encrypt(value)
rsa_public_encrypt(value, @public_key)
end
# 公密解密
def public_decrypt(value)
rsa_private_decrypt(value, @private_key)
end
private
def rsa_private_encrypt(value, rsakey)
rsa = OpenSSL::PKey::RSA.new(rsakey)
rsa.private_encrypt(value)
end
def rsa_private_decrypt(value, rsakey)
rsa = OpenSSL::PKey::RSA.new(rsakey)
rsa.private_decrypt(value)
end
def rsa_public_encrypt(value, publickey)
rsa = OpenSSL::PKey::RSA.new(publickey)
rsa.public_encrypt(value)
end
def rsa_public_decrypt(value, publickey)
rsa = OpenSSL::PKey::RSA.new(publickey)
rsa.public_decrypt(value)
end
end
3. DES-EDE3加密
require "openssl"
require "base64"
class EncryptDes
def initialize()
@encrypt = OpenSSL::Cipher::Cipher.new("DES-EDE3")
end
# DES 加密
def encrypt(key, text)
@encrypt.key = key
@encrypt.encrypt
s = @encrypt.update text
s << @encrypt.final
Base64.encode64(s)
end
# DES 解密
def decrypt(key, encrypt_value)
_value = Base64.decode64(encrypt_value)
@encrypt.key = key
@encrypt.decrypt
ret = @encrypt.update(_value)
ret << @encrypt.final
end
end
使用如下:
des = EncryptDes.new
des.encrypt(key, uncrypt_str)
des.decrypt(key, encrypt_value)