Created
September 26, 2016 09:38
-
-
Save ik5/5790ea16714ac750d6e95392598806e5 to your computer and use it in GitHub Desktop.
quick and dirty pki generator using ruby
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
require 'openssl' | |
require 'base64' | |
root_key = OpenSSL::PKey::RSA.new 2048 # the CA's public/private key | |
root_ca = OpenSSL::X509::Certificate.new | |
root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate | |
root_ca.serial = 1 | |
root_ca.subject = OpenSSL::X509::Name.parse "/DC=org/DC=ruby-lang/CN=Ruby CA" | |
root_ca.issuer = root_ca.subject # root CA's are "self-signed" | |
root_ca.public_key = root_key.public_key | |
root_ca.not_before = Time.now | |
root_ca.not_after = root_ca.not_before + 2 * 365 * 24 * 60 * 60 # 2 years validity | |
ef = OpenSSL::X509::ExtensionFactory.new | |
ef.subject_certificate = root_ca | |
ef.issuer_certificate = root_ca | |
root_ca.add_extension(ef.create_extension("basicConstraints","CA:TRUE",true)) | |
root_ca.add_extension(ef.create_extension("keyUsage","keyCertSign, cRLSign", true)) | |
root_ca.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false)) | |
root_ca.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false)) | |
root_ca.sign(root_key, OpenSSL::Digest::SHA256.new) | |
key = OpenSSL::PKey::RSA.new 2048 | |
cert = OpenSSL::X509::Certificate.new | |
cert.version = 2 | |
cert.serial = 2 | |
cert.subject = OpenSSL::X509::Name.parse "/DC=org/DC=ruby-lang/CN=Ruby certificate" | |
cert.issuer = root_ca.subject # root CA is the issuer | |
cert.public_key = key.public_key | |
cert.not_before = Time.now | |
cert.not_after = cert.not_before + 1 * 365 * 24 * 60 * 60 # 1 years validity | |
ef = OpenSSL::X509::ExtensionFactory.new | |
ef.subject_certificate = cert | |
ef.issuer_certificate = root_ca | |
cert.add_extension(ef.create_extension("keyUsage","digitalSignature", true)) | |
cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false)) | |
cert.sign(root_key, OpenSSL::Digest::SHA256.new) | |
File.write('/tmp/new_key.key', key.to_pem) | |
File.write('/tmp/new_cert.cert', cert.to_pem) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment