【问题标题】:AES Encryption losing end of XSL fileAES 加密丢失 XSL 文件的结尾
【发布时间】:2020-03-09 14:34:48
【问题描述】:

我正在尝试使用 AES 加密来加密保存在 MongoDB 上的文件。 这使用了 GridFS gem。

AES 密钥由 RSA 自行加密,然后与文档一起存储在 Mongo 中。

我之前使用 Mongoid::EncryptedFields.cipher.encrypt 工作正常,但是,客户希望使用 RSA 密钥。

我的 xsl_action:

tempFile = params[:stylesheet].tempfile
file = File.open(tempFile)

grid_fs = Mongoid::GridFS

#Encryption
pub_file = CaseCenter::Config::Reader.get('pub_key');
public_key = OpenSSL::PKey::RSA.new(File.read(pub_file))
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.encrypt
key = cipher.random_key
encData = cipher.update(File.read(file))
#End Encryption

File.open(file, 'wb') do |f|
  f.write(encData)
end
encrypted_aes = Base64.encode64(public_key.public_encrypt(key))
stylesheet.aes_key = encrypted_aes

grid_file = grid_fs.put(file.path)
stylesheet.stylesheet_id = grid_file.id

为了解密文件,我使用这个:

grid_fs = Mongoid::GridFs
f = grid_fs.get(stylesheet_id)

#Decryption
key = CaseCenter::Config::Reader.get('priv_key')
passphrase = CaseCenter::Config::Reader.get('key_pass')
if key.include? "-----BEGIN RSA PRIVATE KEY-----"
  private_key = OpenSSL::PKey::RSA.new(key,passphrase)
else
  private_key = OpenSSL::PKey::RSA.new(File.read(key),passphrase)
end
decKey = private_key.private_decrypt(Base64.decode64(doc[:aes_key]))
cipher = OpenSSL::Cipher.new('aes-256-cbc')
cipher.decrypt
cipher.key = decKey
decData = cipher.update(f.data)

AES 密钥和文件已正确加密,但是在解密时,文件会丢失最后 30 个字符。 我在加密期间做错了吗?

编辑 1: 以为可能是我没有包含 cipher.final。

我现在已经包含了

encData << cipher.final

我仍然遇到同样的问题,不是所有文件都被返回,但是,现在丢失的字符更少了。 我现在假设这个问题是由于初始加密阶段造成的。

【问题讨论】:

  • 分离存储和加密,找出问题所在。验证您存储在 gridfs 中的数据是否已完全取回,单独验证您的解密是否正确。
  • @D.SM 我已经确认存储在 gridfs 中的数据已完全检索回来。我已经能够对图像文件进行这种类型的加密/解密,但是我遇到了 XML 文档的这个问题。

标签: ruby-on-rails openssl aes rsa mongoid


【解决方案1】:

对于其他可能遇到相同问题的人,我忘记在加密和解密中都包含 cipher.final。

#Encryption
encData << cipher.final

#Decryption
decData << cipher.final

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-23
    • 2013-12-06
    • 2013-03-16
    • 2014-07-01
    • 1970-01-01
    • 2015-02-23
    • 2011-08-03
    相关资源
    最近更新 更多