Skip to content

Instantly share code, notes, and snippets.

@ogaida
Last active June 30, 2022 20:45
Show Gist options
  • Save ogaida/85d7ed56935d522dc3a763eb39c5bda7 to your computer and use it in GitHub Desktop.
Save ogaida/85d7ed56935d522dc3a763eb39c5bda7 to your computer and use it in GitHub Desktop.
create json from a certificate fullchain.pem
#!/usr/bin/env ruby
require 'openssl'
require "json"
fullchain = ARGV[0]
cmd = %(openssl crl2pkcs7 -nocrl -certfile #{fullchain} | openssl pkcs7 -print_certs)
# if problems with empty lines occur, use this:
# cmd = %(openssl crl2pkcs7 -nocrl -certfile #{fullchain} | openssl pkcs7 -print_certs | perl -pe 's/^\n$//mg; s/-----END CERTIFICATE-----/-----END CERTIFICATE-----\n/' )
out = `#{cmd}`
certs = out.split(/\n\n/)
certsArr = []
certs.each do |certpem|
h = {}
cert = OpenSSL::X509::Certificate.new(certpem)
cert.extensions.each do |ext|
a = ext.to_a
case a[0]
when "subjectKeyIdentifier"
h[a[0]] = [a[1]][0]
when "subjectAltName"
h[a[0]] = ([a[1]][0].split(/,/).map do |name|; name.sub!(/^\s*DNS:/,""); end).join(",")
when "authorityKeyIdentifier"
h[a[0]] = [a[1]][0].chop.sub(/^keyid:/,"")
end
end
h["not_after"] = cert.not_after
h["not_after_epoche"] = cert.not_after.to_i
h["not_before"] = cert.not_before
h["not_before_epoche"] = cert.not_before.to_i
subHash = {}
cert.subject.to_a.each do |e|; subHash[e[0]] = e[1]; end
h["CN"] = subHash["CN"]
subArray = []
cert.subject.to_a.each do |e|; subArray << "#{e[0]}=#{e[1]}"; end
h["subject"] = subArray.join(",")
certsArr << h
end
puts JSON.pretty_generate(certsArr)
@ogaida
Copy link
Author

ogaida commented Jun 30, 2022

Output:

grafik

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment