Skip to content

Instantly share code, notes, and snippets.

@danhodge
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save danhodge/37237e02b19cf1578138 to your computer and use it in GitHub Desktop.

Select an option

Save danhodge/37237e02b19cf1578138 to your computer and use it in GitHub Desktop.
Dealing with Certificates
require "base64"
require "digest"
require "openssl"
# openssl req -in <csr_file> -noout -pubkey
def extract_public_key_from_csr(csr_file)
csr = OpenSSL::X509::Request.new(File.read(csr_file))
csr.public_key.to_pem
end
# openssl x509 -inform der -in <cer_file> -noout -text
def extract_public_key_from_cert(cer_file)
cert = OpenSSL::X509::Certificate.new(File.read(cer_file))
cert.public_key.to_pem
end
def csr_matches_cert?(csr_file, cert_file)
extract_public_key_from_csr(csr_file) == extract_public_key_from_cert(cert_file)
end
# Computes the SHA-256 hash of the public key given a certificate file and returns
# it in the same format that it appears in an Apple Pay payment token
def compute_public_key_hash(cert_file)
cert = OpenSSL::X509::Certificate.new(File.read(cert_file))
# strip off the "-----BEGIN PUBLIC KEY-----" line at the start of the string
pem = cert.public_key.to_pem.split("\n").drop(1)
# strip off the "-----END PUBLIC KEY-----" line at the end of the string
pem = pem.take(pem.length - 1)
decoded = Base64.decode64(pem.join)
Digest::SHA256.base64digest(decoded)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment