封装了两个加密小工具(des, rsa加密)

旧城冷巷雨未停 提交于 2020-01-07 20:12:47

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

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)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!