无法使用另一个密码实例解密加密的消息

Unable to decrypt encrypted message using another instance of cipher

我正在使用 ruby 版本 2.4.0 和 openssl 版本 "OpenSSL 1.0.1f 6 Jan 2014",我正在尝试为安全层实施 encryption/decryption。

如果我使用相同的密码对象按如下方式编写代码,则代码工作正常。

# Example 1

require 'openssl'
require 'base64'

data = "Hello1"

cipher = OpenSSL::Cipher::AES128.new :GCM
cipher.encrypt
iv  = cipher.random_iv # random iv
key = cipher.random_key # 128 byte key
cipher.key = key
cipher.iv = iv
enc_data  = cipher.update(data) + cipher.final

cipher.decrypt
cipher.key = key
cipher.iv = iv
original_data = cipher.update(enc_data) + cipher.final

if data == original_data
  puts "Yes"
end

但是在第二个示例中,我实例化了第二个用于解密的密码对象,但出现了 CipherError。

# Example 1

require 'openssl'
require 'base64'

def encrypt(data)
  cipher = OpenSSL::Cipher::AES128.new :GCM
  cipher.encrypt
  key = cipher.random_key
  iv  = cipher.random_iv
  cipher.key = key
  cipher.iv = iv
  enc_data = cipher.update(data) + cipher.final
  return enc_data, key, iv
end

def decrypt(data, key, iv)
  cipher = OpenSSL::Cipher::AES128.new :GCM
  cipher.decrypt
  cipher.key = key
  cipher.iv  = iv
  cipher.update(data) + cipher.final
end

data = 'Hello2'
enc_data, key, iv = encrypt(data)
original_data = decrypt(enc_data, key, iv)

if data == original_data
  puts "Yes"
end


OpenSSL::Cipher::CipherError:
from (irb):93:in `final'
from (irb):93:in `decrypt'
from (irb):98

与 CBC 模式相比,GCM 模式需要更多设置。

文档:https://ruby-doc.org/stdlib-2.4.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Authenticated+Encryption+and+Associated+Data+-28AEAD-29

An example using the GCM (Galois/Counter Mode). You have 16 bytes key, 12 bytes (96 bits) nonce and the associated data auth_data. ... Now you are the receiver. You know the key and have received nonce, auth_data, encrypted and tag through an untrusted network.

这是更新后的代码:

require 'openssl'
require 'base64'

def encrypt(data)
  cipher = OpenSSL::Cipher::AES128.new(:GCM).encrypt
  key = cipher.random_key
  iv  = cipher.random_iv
  cipher.key = key
  cipher.iv = iv
  cipher.auth_data = ''
  enc_data = cipher.update(data) + cipher.final
  return enc_data, key, iv, cipher.auth_tag
end

def decrypt(data, key, iv, auth_tag)
  cipher = OpenSSL::Cipher::AES128.new(:GCM).decrypt
  cipher.decrypt
  cipher.key = key
  cipher.iv  = iv
  cipher.auth_data = ''
  cipher.auth_tag = auth_tag
  cipher.update(data) + cipher.final
end

data = 'Hello2'
enc_data, key, iv, auth_tag = encrypt(data)
original_data = decrypt(enc_data, key, iv, auth_tag)

if data == original_data
  puts "Yes"
end