Ruby: file encryption/decryption with private/public keys

前端 未结 4 1017
醉话见心
醉话见心 2020-12-05 04:53

I am searching for an algorithm for file encryption/decryption which satisfies the following requirements:

  • Algorithm must be reliable
  • Algorithm should
4条回答
  •  孤城傲影
    2020-12-05 05:44

    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

提交回复
热议问题