Ruby-加密算法AES

 

高级加密标准英语Advanced Encryption Standard缩写AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

 

require 'openssl'
require 'base64'

# usage: 

# KEY = "***************************************"

# puts AesEncryptDecrypt.encryption(KEY, "gurudath", "AES-128-ECB")
# puts AesEncryptDecrypt.decryption(KEY, "mCwOIMl+EG2DFUkIaOHCpQ==", "AES-128-ECB")
# mCwOIMl+EG2DFUkIaOHCpQ==
# gurudath

# puts AesEncryptDecrypt.encryption(KEY, "gurudath", "AES-256-CBC")
# puts AesEncryptDecrypt.decryption(KEY, "jbhZh7fl0oUAM1xU+kQyAw==", "AES-256-CBC")
# jbhZh7fl0oUAM1xU+kQyAw==
# gurudath

class AesEncryptDecrypt

  def self.encryption(key, msg, algorithm)
    begin
      cipher = OpenSSL::Cipher.new(algorithm)
      cipher.encrypt()
      cipher.key = key
      crypt = cipher.update(msg) + cipher.final()
      crypt_string = (Base64.encode64(crypt))
      return crypt_string
    rescue Exception => exc
      puts ("Message for the encryption log file for message #{msg} = #{exc.message}")
    end
  end
  
  def self.decryption(key, msg, algorithm)
    begin
      cipher = OpenSSL::Cipher.new(algorithm)
      cipher.decrypt()
      cipher.key = key
      tempkey = Base64.decode64(msg)
      crypt = cipher.update(tempkey)
      crypt << cipher.final()
      return crypt
    rescue Exception => exc
      puts ("Message for the decryption log file for message #{msg} = #{exc.message}")
    end
  end
end


更多精彩内容清关注微信订阅号: Ruby程序员

 

 

 

 

 

你可能感兴趣的:(aes,encrypt)