1

I'm having difficulty to Encrypt large files (bigger than available memory) using GPGME in Ruby.

#!/usr/bin/ruby
require 'gpgme'

def gpgfile(localfile)
  crypto = GPGME::Crypto.new
  filebasename = File.basename(localfile)
  filecripted = crypto.encrypt File.read(localfile), :recipients => "info@address.com", :always_trust => true
  File.open("#{localfile}.gpg", 'w') { |file| file.write(filecripted) }
end

gpgpfile("/home/largefile.data")

In this case I got an error of memory allocation: "read: failed to allocate memory (NoMemoryError)"

Someone can explain me how to read the source file chunk by chunk (of 100Mb for example) and write them passing by the crypting?

4

1 回答 1

1

最明显的问题是您使用File.read(localfile). 该Crypto#encrypt方法将一个 IO 对象作为其输入,因此File.read(localfile)您可以传递一个 File 对象而不是(将文件的内容作为字符串返回)。同样,您可以提供一个 IO 对象作为:output选项,让您将输出直接写入文件而不是内存中:

def gpgfile(localfile)
  infile = File.open(localfile, 'r')
  outfile = File.open("#{localfile}.gpg", 'w')

  crypto = GPGME::Crypto.new    
  crypto.encrypt(infile, recipients: "info@address.com",
                         output: outfile,
                         always_trust: true)
ensure
  infile.close
  outfile.close
end

我从来没有使用过 ruby​​-gpgme,所以我不能 100% 确定这会解决你的问题,因为它在某种程度上取决于 ruby​​-gpgme 在幕后所做的事情,但是从文档和我偷看的源代码中看起来像是一个精心打造的宝石,所以我猜这会成功。

于 2016-01-21T18:10:05.573 回答