gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:02 26 4
gpt4 key购买 nike

我正在使用 ruby​​ 版本 2.4.0 和 openssl 版本“OpenSSL 1.0.1f 6 Jan 2014”,我正在尝试为安全层实现加密/解密。

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

# 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

关于ruby - 无法使用另一个密码实例解密加密的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com