Ruby GPGME-如何加密大文件 [英] Ruby GPGME - How to encrypt large files
问题描述
我很难在Ruby中使用GPGME加密大文件(大于可用内存).
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")
在这种情况下,我得到了内存分配错误: 读取:分配内存失败(NoMemoryError)"
In this case I got an error of memory allocation: "read: failed to allocate memory (NoMemoryError)"
有人可以解释我如何逐块读取源文件(例如100Mb)并通过加密将它们写入吗?
Someone can explain me how to read the source file chunk by chunk (of 100Mb for example) and write them passing by the crypting?
推荐答案
最明显的问题是,您正在使用File.read(localfile)
将整个文件读取到内存中. Crypto#encrypt
方法将采用IO对象作为输入,因此可以代替File.read(localfile)
(它以字符串形式返回文件的内容),而可以向其传递File对象.同样,您可以将IO对象作为:output
选项,使您可以将输出直接写到文件中,而不是写在内存中:
The most obvious problem is that you're reading the entire file into memory with File.read(localfile)
. The Crypto#encrypt
method will take an IO object as its input, so instead of File.read(localfile)
(which returns the contents of the file as a string) you can pass it a File object. Likewise, you can give an IO object as the :output
option, letting you write the output directly to a file instead of in memory:
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在幕后所做的事情,但是取决于我的文档和来源偷看它似乎是一颗疯狂建造的宝石,所以我猜想这可以解决问题.
I've never used ruby-gpgme, so I'm not 100% sure this will solve your problem since it depends a bit on what ruby-gpgme does behind the scenes, but from the docs and the source I've peeked at it seems like a sanely-built gem so I'm guessing this will do the trick.
这篇关于Ruby GPGME-如何加密大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!