gpt4 book ai didi

ruby - 加密空字符串

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

我正在使用 Ruby 的 Open SSL bindings进行 AES-256 加密。我可以加密一个非空字符串。但是,当尝试加密空字符串时,Ruby 会引发异常,提示数据不能为空。 如何使用 Ruby 的 OpenSSL 绑定(bind)加密空字符串?

重现问题的代码

require "openssl"

KEY = OpenSSL::Cipher::Cipher.new("aes-256-cbc").random_key

def encrypt(plaintext)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
iv = cipher.random_iv
cipher.iv = iv
cipher.key = KEY
ciphertext = cipher.update(plaintext) # <- ArgumentError here
ciphertext << cipher.final
[iv, ciphertext]
end

def decrypt(iv, ciphertext)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.iv = iv
cipher.key = KEY
plaintext = cipher.update(ciphertext)
plaintext << cipher.final
plaintext
end

p decrypt(*encrypt("foo")) # "foo"

p decrypt(*encrypt(""))
# /tmp/foo.rb:11:in `update': data must not be empty (ArgumentError)
# from /tmp/foo.rb:11:in `encrypt'
# from /tmp/foo.rb:27:in `<main>'

版本

  • ruby-2.2.2p95
  • OpenSSL::VERSION 为“1.1.0”
  • 微软 SQL Server 2014 (12.0.2000.8)

为什么要加密空字符串?

我正在写一个 ETL将数据从一个数据库迁移到 SqlServer 数据库的程序。源数据库中的某些列在写入目标数据库之前必须加密。源列可能包含任何数据,包括空字符串。目标列通常是不可空的。目标列将由 .net 代码解密。

目标 1:在不正确解密的情况下,不应恢复有关加密字段的信息,包括它是否存在。加密的空字符串应该与任何其他加密数据没有区别。

目标 2:将解密这些值的 .net 代码不需要专门处理空字符串。

如果我能让 openssl 加密空字符串,我将实现这两​​个目标。

解决方法 - 不要加密空字符串

我不能加密空字符串,让它们通过。

def encrypt(plaintext)
return plaintext if plaintext.empty?
...
end

def decrypt(iv, ciphertext)
return ciphertext if ciphertext.empty?
...
end

这有暴露信息的缺点,也需要在 .net 端编写协作代码。

解决方法——向明文添加一些常量

我可以在加密前向明文添加一些常量字符串,并在解密后将其删除:

PLAINTEXT_SUFFIX = " "

def encrypt(plaintext)
plaintext += PLAINTEXT_SUFFIX
...
end

def decrypt(iv, ciphertext)
...
plaintext.chomp(PLAINTEXT_SUFFIX)
end

这隐藏了数据是否存在,但仍然需要配合.net代码。

最佳答案

As suggested by @ArtjomB , 就像不调用 Cipher#update 一样简单用空字符串。 Cipher#final 返回的值然后正确地加密一个空字符串。

require "openssl"

KEY = OpenSSL::Cipher::Cipher.new("aes-256-cbc").random_key

def encrypt(plaintext)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt
iv = cipher.random_iv
cipher.iv = iv
cipher.key = KEY
ciphertext = ""
ciphertext << cipher.update(plaintext) unless plaintext.empty?
ciphertext << cipher.final
[iv, ciphertext]
end

def decrypt(iv, ciphertext)
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.iv = iv
cipher.key = KEY
plaintext = cipher.update(ciphertext)
plaintext << cipher.final
end

p decrypt(*encrypt("foo")) # "foo"
p decrypt(*encrypt("")) # ""

关于ruby - 加密空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35068856/

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