gpt4 book ai didi

Ruby 从预先存在的 key 字符串创建密码 key

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

使用 OpenSSL CLI,我可以使用我能找到的任何 ASCII 字符串来加密值,只要它符合加密方法所需的长度即可。

例如:

printf 'flipflop' | openssl enc -K 2317823178123897237891232345345234524523452345 -iv 123789123789123789 -base64 -aes-256-cbc

Pd4+UEBW1RyTjARy1rpndQ==

printf 'Pd4+UEBW1RyTjARy1rpndQ==\n' | openssl enc -d -K 2317823178123897237891232345345234524523452345 -iv 123789123789123789 -base64 -aes-256-cbc

flipflop

但是,如果我拿到那个 key ,然后我们用 Ruby 运行它:

require 'openssl'

cipher = OpenSSL::Cipher::Cipher.new 'AES-256-CBC'
cipher.encrypt
cipher.key = "2317823178123897237891232345345234524523452345"
cipher.iv = "123789123789123789"
encrypted = cipher.update "flipflop" + cipher.final
puts encrypted

cipher = OpenSSL::Cipher::Cipher.new 'AES-256-CBC'
cipher.decrypt
cipher.key = "2317823178123897237891232345345234524523452345"
cipher.iv = "123789123789123789"
plain = cipher.update(encrypted) + cipher.final
puts plain

���ISq��Ҷ0�e�
crypt.rb:14:in `final': bad decrypt (OpenSSL::Cipher::CipherError)
from crypt.rb:14:in `<main>'

此外,当我从 openssl 命令中获取 base64 时,我得到了同样的错误解密:

require 'openssl'
require 'base64'

clear = Base64.decode64("Pd4+UEBW1RyTjARy1rpndQ==")

cipher = OpenSSL::Cipher::Cipher.new 'AES-256-CBC'
cipher.decrypt
cipher.key = "2317823178123897237891232345345234524523452345"
cipher.iv = "123789123789123789"
plain = cipher.update(clear) + cipher.final
puts plain

crypt.rb:10:in `final': bad decrypt (OpenSSL::Cipher::CipherError)
from crypt.rb:10:in `<main>'

我认为这里发生的是 OpenSSL 正在以一种方式转换我的密码 key 和 IV,而 ruby​​ 正在以另一种方式进行转换。例如,当您使用 PBKDF2 创建 key 时,您会得到一串十六进制值,即:“\x00\AF...”。

这是手头的问题吗?我需要将我的字符串转换成特定格式吗?我怎么做?这不是问题所在吗?

最佳答案

这里有几个问题。

由于这一行,您的 Ruby 往返代码无法正常工作:

encrypted = cipher.update "flipflop" + cipher.final

应该是:

encrypted = cipher.update("flipflop") + cipher.final

这是导致 bad decrypt 错误的错误加密。否则该代码应该可以工作,尽管它使用的 key 和 ivs 与命令行版本不同。但是,它只适用于旧版本的 Ruby 和 OpenSSL 绑定(bind)。 Ruby 的 OpenSSL 库的当前版本检查提供的 keyiv 的长度,如果它们错误则引发异常。对于 aes-256-cbc,它们应该分别为 32 和 16 字节。

openssl enc 命令的 -K-iv 选项接受十六进制编码字符串,然后将其解码为原始字节。它还用零字节填充这些值,直到它们达到正确的长度。

以下是在 Ruby 中解密命令行加密字符串的方法:

# Base64 cipher text from the question:
message = "Pd4+UEBW1RyTjARy1rpndQ=="
message = Base64.decode64(message)

key = "2317823178123897237891232345345234524523452345"
#Convert from hex to raw bytes:
key = [key].pack('H*')
#Pad with zero bytes to correct length:
key << ("\x00" * (32 - key.length))

iv ="123789123789123789"
#Convert from hex to raw bytes:
iv = [iv].pack('H*')
#Pad with zero bytes to correct length:
iv << ("\x00" * (16 - iv.length))

cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.decrypt
cipher.key = key
cipher.iv = iv
plain = cipher.update(message) + cipher.final
puts plain # => 'flipflop'

关于Ruby 从预先存在的 key 字符串创建密码 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231431/

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