使用Ruby中的3DES从.NET解密十六进制字符串

时间:2016-10-19 00:49:26

标签: ruby encryption 3des

我正在研究一个与我正在与之交换一些加密数据的网络服务进行交互的Ruby项目。

我很难解密我从Ruby的Web服务中获得的东西,尽管在.NET方面,它运行良好,而且许多其他基于Web或基于桌面的工具可以解决这个问题。

加密方法是使用ECB且没有填充的3DES。

以下是我一直在研究的测试脚本。我已经尝试了所有我能想到的东西来正确解开这些字符串,但无济于事。

require 'openssl'
require 'base64'

def cipher(key, encrypted)
  key = key.unpack('a2'*32).map{|x| x.hex}.pack('c'*32)
  encrypted = encrypted.unpack('a2'*32).map{|x| x.hex}.pack('c'*32)
  OpenSSL::Cipher::ciphers.select{|c| c.include? 'des3' }.map do |cipher_name|
    begin
      cipher = OpenSSL::Cipher.new(cipher_name)
      cipher.padding = 0
      cipher.decrypt
      cipher.key=key

      plain = cipher.update(encrypted) + cipher.final

      p "Cipher #{cipher_name} success: #{plain} #{plain.class} #{plain.length} #{plain.encoding.to_s}"
      plain
    rescue => e
      p "Cipher #{cipher_name} failed #{e}"
      nil
    end
  end

end

key = '202FA9B21843D7022B6466DB68327E1F'
encrypted = 'ff6f07e270ebd5c0878c67c999d87ebf'

res1 = cipher key, encrypted

key = '49CE85147B24123718AB3F4539AB1A21'
encrypted = '995604ed8016da8897f1875ebd725529'

res2 = cipher key, encrypted


p res1 == res2 ? "SUCCESS" : "FAIL"

# In both cases, the correct output should be '25588015543912470222703296730936'

BC-Tools Decryption

1 个答案:

答案 0 :(得分:1)

3DES密钥为24字节,使用全长密钥。

3DES使用三重加密,基本上是一个24字节的密钥。 202FA9B21843D7022B6466DB68327E1F是十六进制编码的16字节密钥。

尝试重复密钥的前8个字节:
202FA9B21843D7022B6466DB68327E1F202FA9B21843D702

一些3DES实现将重复8字节的16字节密钥,但依赖于此类实现细节并不是一个好主意。

注意:3DES实际上使用168位密钥,因为不使用每个字节的LSb。此外,因为实际上存在三个DES调用,所以安全性仅为112位。另外,DES有一些弱键。有两种常见的模式,ede和ded,以便于从DES转移到3DES,从而增加了更多的混淆。

最后:使用随机IV在CBC模式下从3DES移动到AES。请不要继续执行不良安全措施。

相关问题