Skip to content

Instantly share code, notes, and snippets.

@zmajstor
Created August 18, 2014 22:58
Show Gist options
  • Save zmajstor/2d1656228be6acd36743 to your computer and use it in GitHub Desktop.
Save zmajstor/2d1656228be6acd36743 to your computer and use it in GitHub Desktop.
require 'OpenSSL'
class KeyPair
attr_reader :key, :cert
def initialize serial, issuer=nil
@key = OpenSSL::PKey::RSA.new(1024)
@cert = OpenSSL::X509::Certificate.new
@cert.version = 2 # RFC 5280 - v3
@cert.serial = serial
@cert.subject = OpenSSL::X509::Name.parse "CN=#{serial}"
@cert.issuer = issuer==nil ? @cert.subject : issuer
@cert.public_key = @key.public_key
@cert.not_before = Time.now
@cert.not_after = Time.mktime(2015, 1, 19, 11, 14, 7)
@cert.sign(@key, OpenSSL::Digest::SHA1.new) if issuer == nil
end
def sign key
# ...
end
def encrypt_sign(plain, receiver_cert)
# ...
end
def verify_decrypt(received, receiver_cert, ca_cert)
# ...
end
end
ca = KeyPair.new(1)
alice = KeyPair.new(11, ca.cert.issuer)
alice.sign ca.key
bob = KeyPair.new(12, ca.cert.issuer)
bob.sign ca.key
plain = "It's okay!"
signed_encrypted = alice.encrypt_sign(plain, bob.cert)
decrypted = bob.verify_decrypt(signed_encrypted, bob.cert, ca.cert)
puts (decrypted == plain) ? plain : "not ok!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment