Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby code for doing P12 to PEM conversion via command line. Supports MRI/JRuby/Rubinius
require 'tempfile'
require 'openssl'
require 'escape' # gem install escape
class CommandFailError < StandardError; end
def p12_to_pem_text(p12, pass='')
pass = '' if pass.nil?
# Use shell command for JRuby (see https://github.com/jruby/jruby-ossl/issues/8)
if RUBY_PLATFORM == 'java'
tf_p12 = Tempfile.new 'tf_p12'
tf_p12.write p12
tf_p12.close
tf_pem = Tempfile.new 'tf_pem'
tf_pem.close
cmd = Escape.shell_command(['openssl', 'pkcs12', '-in', tf_p12.path, '-out', tf_pem.path,
'-nodes', '-clcerts', '-password', 'pass:'+pass]).to_s + ' &> /dev/null'
begin
result = system cmd
raise CommandFailError if result.nil? || result == false
pem = File.read tf_pem.path
ensure
tf_pem.unlink
tf_p12.unlink
end
pem
else
# Use PKCS12 class for everything else (works in MRI/Rubinius)
pkcs12 = OpenSSL::PKCS12.new p12, pass
pkcs12.certificate.to_s + pkcs12.key.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment