我正在用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中实现相同类型的加密呢?
发布于 2017-10-02 22:15:11
考虑到我们使用的是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,这是一个有用的答案。
发布于 2017-10-02 20:03:10
您可以将字节数组打包到字符串中:
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]https://stackoverflow.com/questions/46532553
复制相似问题