Skip to content

Instantly share code, notes, and snippets.

@emboss
Created December 13, 2011 02:57
Show Gist options
  • Save emboss/1470287 to your computer and use it in GitHub Desktop.
Save emboss/1470287 to your computer and use it in GitHub Desktop.
Encode pre-1.9.3 RSA public keys using X.509 format
require 'openssl'
require 'base64'
rsa = OpenSSL::PKey::RSA.new(2048)
modulus = rsa.n
exponent = rsa.e
oid = OpenSSL::ASN1::ObjectId.new("rsaEncryption")
alg_id = OpenSSL::ASN1::Sequence.new([oid, OpenSSL::ASN1::Null.new(nil)])
ary = [OpenSSL::ASN1::Integer.new(modulus), OpenSSL::ASN1::Integer.new(exponent)]
pub_key = OpenSSL::ASN1::Sequence.new(ary)
enc_pk = OpenSSL::ASN1::BitString.new(pub_key.to_der)
subject_pk_info = OpenSSL::ASN1::Sequence.new([alg_id, enc_pk])
base64 = Base64.encode64(subject_pk_info.to_der)
#This is the equivalent to the X.509 encoding used in >= 1.9.3
pem = "-----BEGIN PUBLIC KEY-----\n#{base64}-----END PUBLIC KEY-----"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment