Ruby:使用私钥/公钥进行文件加密/解密
问题描述:
我正在搜索一种满足以下要求的文件加密/解密算法:
I am searching for an algorithm for file encryption/decryption which satisfies the 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)
是否有任何Ruby实现建议的算法?
Is there any Ruby implementation of suggested algorithms?
答
注意:评论,这个答案是不适合一个实际的系统。首先,文件加密不应该使用这种方法(例如,lib提供AES)。其次,这个答案并没有解决任何更广泛的问题,也会影响你如何设计你的解决方案。
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.
原始来源也进入更多细节。
Ruby可以使用openssl来执行此操作:
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))
并解密:
#!/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