Ruby on rails 在ruby中获取错误的解密

Ruby on rails 在ruby中获取错误的解密,ruby-on-rails,ruby,Ruby On Rails,Ruby,我使用此代码片段扩展Rails中的字符串类: require 'openssl' class String def encrypt(key) cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt key = cipher.random_key cipher.key = key s = cipher.update(self) + cipher.final s.unpack('H*')[0].upca

我使用此代码片段扩展Rails中的
字符串
类:

require 'openssl'

class String
  def encrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
    key = cipher.random_key
    cipher.key = key
    s = cipher.update(self) + cipher.final

    s.unpack('H*')[0].upcase
  end

  def decrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
    key = cipher.random_key
    cipher.key = key
    s = [self].pack("H*").unpack("C*").pack("c*")

    cipher.update(s) + cipher.final
  end
end
但是,在对字符串进行解密时,我得到了“错误的解密错误”:

我尝试在解密操作中添加这样的填充(类似于SO问题):


错误消失了,但我得到的是胡言乱语。

即使您将密钥(
secret
)传递给加密和解密函数,您也在使用下面提到的代码重新定义密钥

key = cipher.random_key
您应该对加密和解密使用相同的密钥。 请尝试以下代码段:

require 'openssl'

class String
  def encrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
    cipher.key = (Digest::SHA1.hexdigest key)[0..23]
    s = cipher.update(self) + cipher.final

    s.unpack('H*')[0].upcase
  end

  def decrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
    cipher.key = (Digest::SHA1.hexdigest key)[0..23]
    s = [self].pack("H*").unpack("C*").pack("c*")

    cipher.update(s) + cipher.final
  end
end



puts plain = 'confidential'           # confidential
puts key = 'secret'                   # secret
puts cipher = plain.encrypt(key)      # 5C6D4C5FAFFCF09F271E01C5A132BE89


puts cipher.decrypt(key)              # confidential

即使您将密钥(
secret
)传递给加密和解密函数,您也会使用下面提到的代码重新定义密钥

key = cipher.random_key
您应该对加密和解密使用相同的密钥。 请尝试以下代码段:

require 'openssl'

class String
  def encrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').encrypt
    cipher.key = (Digest::SHA1.hexdigest key)[0..23]
    s = cipher.update(self) + cipher.final

    s.unpack('H*')[0].upcase
  end

  def decrypt(key)
    cipher = OpenSSL::Cipher.new('DES-EDE3-CBC').decrypt
    cipher.key = (Digest::SHA1.hexdigest key)[0..23]
    s = [self].pack("H*").unpack("C*").pack("c*")

    cipher.update(s) + cipher.final
  end
end



puts plain = 'confidential'           # confidential
puts key = 'secret'                   # secret
puts cipher = plain.encrypt(key)      # 5C6D4C5FAFFCF09F271E01C5A132BE89


puts cipher.decrypt(key)              # confidential