ruby-on-rails - rails 加密/解密

标签 ruby-on-rails ruby encryption openssl

我需要在我的 Rails 应用程序中进行加密和解密。我正在尝试使用 ezcrypto,但每当我进行解密时,我都会收到此错误。

OpenSSL::Cipher::CipherError in ProfilesController#show

wrong final block length

需要更改什么才能停止此错误。我尝试像这样使用 openssl 的另一个实现(从我的模型中调用的方法)

def encrypt_attr(unencrypted)
    c = OpenSSL::Cipher.new("aes-256-cbc")
    c.encrypt
    c.key = Digest::SHA1.hexdigest('pass')
    e = c.update(unencrypted)
    e << c.final
    return e
end

def decrypt_attr(encrypted_attr)
  if encrypted_attr != ""
    c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
    c.decrypt
    c.key = Digest::SHA1.hexdigest('pass')
    d = c.update(encrypted_attr)
    d << c.final
    return d
  end
end

它在解密时抛出完全相同的错误。我应该如何进行加密和解密而不会出现此 openssl 错误。

最佳答案

require 'openssl'
require 'base64'

class AesEncryptDecrypt

  KEY = "EncryptDecryptGurudathBN"
  ALGORITHM = 'AES-128-ECB'

  def self.encryption(msg)
    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(msg)
    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

加密

irb(main):007:0> AesEncryptDecrypt.encryption('gurudath')
=> "rUPKObydUJd9cY9agm3Glw==\n"

解密

irb(main):008:0> AesEncryptDecrypt.decryption('rUPKObydUJd9cY9agm3Glw==')
=> "gurudath"

关于ruby-on-rails - rails 加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8556940/

相关文章:

ruby-on-rails - Rails 3、Devise、Mandrill、欢迎辞

ruby-on-rails - 无法找到 Rails/Heroku : "The page you were looking for doesn' t exist"的解决方案

python - 如何在不使用任何包的情况下从 django url 加密 pk?

encryption - 使用明文 key 进行 3DES 加密

javascript - TripleDES 在 JavaScript 中加密和解密 - CryptoJS

ruby-on-rails - 查询 Ahoy gem 属性散列

ruby-on-rails - 如何将 FactoryGirl 与 PostGIS 数据库结合使用

ruby-on-rails - RSpec & Tire gem:测试 Tire::Results::Collection

mysql - 使用 ruby​​ 2.0.0 在 Windows 中安装 mysql ruby​​ gem 失败

javascript - 安全地将 Ruby 对象传递给 JavaScript