我正在与一个API交互,该API要求我在AES-128
模式下使用CBC
进行加密。
他们说,对于密钥和IV,我需要使用他们给我的字符串的16字节MD5哈希。
我已经搜索了一段时间,看起来所有MD5都是16字节,那么为什么这不起作用?
key = Digest::MD5.hexdigest(temp_token)
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
cipher.key = key # ArgumentError: key must be 16 bytes
cipher.iv = key # ArgumentError: iv must be 16 bytes
encrypted = cipher.update(joined_params) + cipher.final
Base64.urlsafe_encode64(encrypted)
答案 0 :(得分:0)
问题是我需要改用Digest::MD5.digest
。
答案 1 :(得分:0)
我认为根本原因是OpenSSL::Cipher::AES#key
必须采用16个字节的字符串作为键。
[27] pry(main)> cipher = OpenSSL::Cipher::AES.new(128, :CBC)
=> #<OpenSSL::Cipher::AES:0x00007f7f876f1608>
[28] pry(main)> cipher.encrypt
=> #<OpenSSL::Cipher::AES:0x00007f7f876f1608>
[30] pry(main)> cipher.random_key.length
=> 16
与Digest::MD5.hexdigest
[26] pry(main)> key = Digest::MD5.hexdigest('abc').first(16)
=> "900150983cd24fb0"
[27] pry(main)> cipher = OpenSSL::Cipher::AES.new(128, :CBC)
=> #<OpenSSL::Cipher::AES:0x00007f7f876f1608>
[28] pry(main)> cipher.encrypt
=> #<OpenSSL::Cipher::AES:0x00007f7f876f1608>
[29] pry(main)> cipher.key = key
=> "900150983cd24fb0"