【问题标题】:DES3 decryption in Ruby on RailsRuby on Rails 中的 DES3 解密
【发布时间】:2011-01-03 20:29:09
【问题描述】:

我的 RoR 服务器接收到一个字符串,该字符串在 C++ 应用程序中使用带有 base64 编码的 des3 加密

密码对象是这样创建的:

cipher = OpenSSL::Cipher::Cipher::new("des3")
cipher.key = key_str
cipher.iv =  iv_str

key_str 和 iv_str:是加密算法的密钥和初始化向量的字符串表示。对于 RoR 和 C++ 应用程序,它们是相同的。

RoR端的代码如下:

result = ""
result << cipher.update( Base64.decode64(message) )
result << cipher.final

执行最后一行代码后,我得到一个异常

OpenSSL::CipherError (bad decrypt)

这里有什么问题?有什么想法吗?

【问题讨论】:

  • 最后一行?什么是可变芯片?一个 AR 对象?还有最后的方法是什么?
  • 正如本教程所说,olabini.com/blog/2008/08/ruby-security-quick-guide“最后你需要调用 final 来获取最后生成的密文”我想,这个方法类似于流的刷新方法。

标签: ruby-on-rails ruby encryption encoding openssl


【解决方案1】:

OpenSSL::Cipher 的文档指出:

在使用以下任何方法之前,请务必致电 .encrypt.decrypt 方法:

  • [key=, iv=, random_key, random_iv, pkcs5_keyivgen]

如您所见,在您的特定情况下,省略对 cipher.decrypt 的调用会导致 bad decrypt 错误。

以下示例纠正了该问题并展示了预期的行为:

require 'openssl'
require 'Base64'

# For testing purposes only!
message = 'MyTestString'
key = 'PasswordPasswordPassword'
iv = '12345678'

# Encrypt plaintext using Triple DES
cipher = OpenSSL::Cipher::Cipher.new("des3")
cipher.encrypt # Call this before setting key or iv
cipher.key = key
cipher.iv = iv
ciphertext = cipher.update(message)
ciphertext << cipher.final

puts "Encrypted \"#{message}\" with \"#{key}\" to:\n\"#{ciphertext}\"\n"

# Base64-encode the ciphertext
encodedCipherText = Base64.encode64(ciphertext)

# Base64-decode the ciphertext and decrypt it
cipher.decrypt
plaintext = cipher.update(Base64.decode64(encodedCipherText))
plaintext << cipher.final

# Print decrypted plaintext; should match original message
puts "Decrypted \"#{ciphertext}\" with \"#{key}\" to:\n\"#{plaintext}\"\n\n"

【讨论】:

    【解决方案2】:
    gem install encryptor
    

    它封装了标准的 Ruby OpenSSL 库并允许您使用它的任何算法。

    require 'encryptor'
    Base64.decode64(message).decrypt(:algorithm => 'des', :key => key, :iv => iv)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多