Created
December 10, 2008 04:08
-
-
Save mdp/34221 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # RSA encryption via openssl ruby | |
| # Shamelessly stolen from Leetsoft.com | |
| require 'openssl' | |
| module Crypto | |
| def self.create_keys(priv = "rsa_key", pub = "#{priv}.pub", bits = 1024) | |
| private_key = OpenSSL::PKey::RSA.new(bits) | |
| File.open(priv, "w+") { |fp| fp << private_key.to_s } | |
| File.open(pub, "w+") { |fp| fp << private_key.public_key.to_s } | |
| private_key | |
| end | |
| class Key | |
| def initialize(data) | |
| @public = (data =~ /^-----BEGIN (RSA|DSA) PRIVATE KEY-----$/).nil? | |
| @key = OpenSSL::PKey::RSA.new(data) | |
| end | |
| def self.from_file(filename) | |
| self.new File.read( filename ) | |
| end | |
| def encrypt(text) | |
| Base64.encode64(@key.send("#{key_type}_encrypt", text)) | |
| end | |
| def decrypt(text) | |
| @key.send("#{key_type}_decrypt", Base64.decode64(text)) | |
| end | |
| def private? !@public end | |
| def public? @public end | |
| def key_type | |
| @public ? :public : :private | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment