tiktak tiktak - 6 months ago 27
Ruby Question

Ruby: file encryption/decryption with private/public keys

I search for algorithm for file encryption/decryption which satisfies following requirements:


  • Algorithm must be reliable

  • Algorithm should be fast for rather big files

  • Private key can be generated by some parameter (for example, password)

  • Generated private key must be compatible with public key (public key is generated only once and stored in database)



Is there any ruby implementation of suggested algorythms? Any gem?

Answer

Note Well: As emboss mentions in the comments, this answer is a poor fit for an actual system. Firstly, file encryption should not be carried out using this method (The lib provides AES, for example.). Secondly, this answer does not address any of the wider issues that will also affect how you engineer your solution.

The original source also goes into more details.

Ruby can use openssl to do this:

#!/usr/bin/env ruby

# ENCRYPT

require 'openssl'
require 'base64'

public_key_file = 'public.pem';
string = 'Hello World!';

public_key = OpenSSL::PKey::RSA.new(File.read(public_key_file))
encrypted_string = Base64.encode64(public_key.public_encrypt(string))

And decrypt:

#!/usr/bin/env ruby

# DECRYPT

require 'openssl'
require 'base64'

private_key_file = 'private.pem';
password = 'boost facile'

encrypted_string = %Q{
...
}

private_key = OpenSSL::PKey::RSA.new(File.read(private_key_file),password)
string = private_key.private_decrypt(Base64.decode64(encrypted_string))

from here