使用Ruby加密字节数据

时间:2017-10-02 19:37:47

标签: ruby

我正在开发一个关于使用Ruby进行AES加密的项目。 Ruby的加密库将数据作为字符串获取并开始加密,例如(http://ruby-doc.org/stdlib-2.0.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html)。但是我有一个字节数组数据,如;

seed_V = [0x08,0x06,0x02,0x01,0x03,0x07,0x01]

我想以字节为单位提供数据,并像Java或C#do(Using AES encryption in C#)那样加密 如何在Ruby中进行相同类型的加密?

2 个答案:

答案 0 :(得分:0)

您可以将字节数组打包成字符串:

seed_V = [0x08,0x06,0x02,0x01,0x03,0x07,0x01]
=> [8, 6, 2, 1, 3, 7, 1]

seed_V.pack('C*')
=> "\b\x06\x02\x01\x03\a\x01"

seed_V.pack('C*').unpack('C*')
=> [8, 6, 2, 1, 3, 7, 1]

http://www.rubydoc.info/stdlib/core/Array%3Apack

答案 1 :(得分:0)

考虑一下我们使用的是AES-CBC:

require 'openssl'

class AesCrypto     
  def encrypt(iv, data)
    aes = ::OpenSSL::Cipher.new('AES-128-CBC')
    aes.encrypt
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(data) + aes.final
  end

  def decrypt(iv, encrypted_data)
    aes = ::OpenSSL::Cipher.new('AES-128-CBC')
    aes.decrypt
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(encrypted_data) + aes.final
  end

  private

  def ciphering_key
    # get from config or storage, etc
    'test_key_test_key'
  end
end

请注意,iv长度应等于该CBC的块大小。

seed_v = [0x08,0x06,0x02,0x01,0x03,0x07,0x01,0x08,0x06,0x02,0x01,0x03,0x07,0x01,0x08,0x01]
iv = seed_v.pack('C*')
data = "hello!"

crypto = AesCrypto.new
ciphertext = crypto.encrypt(iv, data)
puts ciphertext
data = crypto.decrypt(iv, ciphertext)
puts data

如果您不确定如何选择iv

,这是一个有用的答案

CBC with a fixed or random IV

相关问题