gpt4 book ai didi

ruby-on-rails - rails openssl 代码和终端加密的不同结果

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:51 26 4
gpt4 key购买 nike

当我尝试加密来自终端的数据时

echo -n "TestData" | openssl enc -aes-256-cbc -a -K C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22 -iv D342F9C6310F6B21E97AB38595BD8CAA

比我收到的Base64编码结果是

VJwJBTtVntJvRGkD24S4wg==

但是当我尝试使用完全相同的 key 和初始化向量对 Rails 进行相同操作时

    cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = "C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22"
cipher.iv = "D342F9C6310F6B21E97AB38595BD8CAA"
encrypted_data = cipher.update("TestData")
encrypted_data << cipher.final
Base64.strict_encode64(encrypted_data)

比我收到完全不同的 Base64 编码结果

qavpNrU7llgauAyyEZz/bw==

谁能指出我错过了什么?

最佳答案

您提供 keyiv 属性作为十六进制字符串,但预期格式是原始字节。使用以下脚本将它们转换为二进制会产生预期的结果:

require 'openssl'
require 'base64'

def hex_to_bin(s)
s.scan(/../).map { |x| x.hex.chr }.join
end

cipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
cipher.encrypt
cipher.key = hex_to_bin("C81E728D9D4C2F636F067F89CC14862C65990ABE58735B91B6B8798E8CE45F22")
cipher.iv = hex_to_bin("D342F9C6310F6B21E97AB38595BD8CAA")
encrypted_data = cipher.update("TestData")
encrypted_data << cipher.final
puts Base64.strict_encode64(encrypted_data)

(hex_to_bin 函数的来源:To Hex and Back (With Ruby))。

调用它encrypt.rb,这是运行它的结果:

$ ruby encrypt.rb 
encrypt.rb:8: warning: constant OpenSSL::Cipher::Cipher is deprecated
VJwJBTtVntJvRGkD24S4wg==

为了摆脱“已弃用”警告,我不得不 replace the deprecated class OpenSSL::Cipher::Cipher with OpenSSL::Cipher .

关于ruby-on-rails - rails openssl 代码和终端加密的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52078744/

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