reidmorrison / symmetric-encryption

Symmetric Encryption for Ruby Projects using OpenSSL
https://logger.rocketjob.github.io/
Apache License 2.0
476 stars 92 forks source link

encrypt / decrypt binary file on disk #80

Open elbarto132 opened 7 years ago

elbarto132 commented 7 years ago

What's the recommended way to encrypt or decrypt large binary files which are stored on the disk? I couldn't find an example in the documentation

reidmorrison commented 7 years ago

It works the same as we would do in code to read or write large files, except using the SymmetricEncryption::Reader:

Create a test file:

SymmetricEncryption::Writer.open('a.txt.enc') {|f| f.write('Hellow world')}

Read from the source file in blocks so that the entire file is not loaded into memory:

SymmetricEncryption::Reader.open('a.txt.enc') do |input|
  File.open('a.txt', 'w') do |output|
    while !input.eof?
      output.write(input.read(65535))
    end
  end
end

There are also rake tasks for encrypting or decrypting files at the command line: https://rocketjob.github.io/symmetric-encryption/rake_tasks.html

Symmetric Encryption v4 will replace the rake tasks with a simpler and more complete command line interface.

elbarto132 commented 7 years ago

Thanks for your reply One note: File.open('a.txt', 'w') do |output| should be File.open('a.txt', 'w', encoding: 'ASCII-8BIT') do |output| or it will throw if you use a binary file

Encoding::UndefinedConversionError: "\xAF" from ASCII-8BIT to UTF-8