ruby-mcrypt为什么不接受数组作为键?

时间:2019-01-02 18:09:51

标签: ruby encryption

您好,我在使用数组作为密钥和ruby-mcrypt gem值进行加密时遇到麻烦。 gem使我可以使用数组来完成键操作,cipher = Mcrypt.new("rijndael-256", :ecb, secret)可以正常工作。但是当我尝试加密时,它将给我一个错误。我尝试了很多事情,但是没有运气。有谁知道Mcrypt是否只是不喜欢使用数组加密?

require 'mcrypt'

def encrypt(plain, secret)
  cipher = Mcrypt.new("rijndael-256", :ecb, secret)
  cipher.padding = :zeros

  encrypted = cipher.encrypt(plain)
  p encrypted
  encrypted.unpack("H*").first.to_s.upcase
end

array_to_encrypt = [16, 0, 0, 0, 50, 48, 49, 55, 47, 48, 50, 47, 48, 55, 32, 50, 50, 58, 52, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
key_array = [65, 66, 67, 68, 49, 50, 51, 52, 70, 71, 72, 73, 53, 54, 55, 56]

result = encrypt(array_to_encrypt, key_array)
p "RESULT IS #{result}"

输出如下:

Mcrypt::RuntimeError: Could not initialize mcrypt: Key length is not legal.

我在ruby-mcrypt宝石中将此错误追溯到here,但是对它的理解不足以弄清为什么我收到错误消息。任何帮助或见解将是惊人的。谢谢!

1 个答案:

答案 0 :(得分:1)

该库不支持数组。您需要改用字符串:

def binary(byte_array)
  byte_array.pack('C*')
end

array_to_encrypt = [16, 0, 0, 0, 50, 48, 49, 55, 47, 48, 50, 47, 48, 55, 32, 50, 50, 58, 52, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
key_array = [65, 66, 67, 68, 49, 50, 51, 52, 70, 71, 72, 73, 53, 54, 55, 56]

result = encrypt(binary(array_to_encrypt), binary(key_array))
p "RESULT IS #{result}"