Skip to content

Instantly share code, notes, and snippets.

@kyledrake
Created July 9, 2012 18:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyledrake/3077989 to your computer and use it in GitHub Desktop.
Save kyledrake/3077989 to your computer and use it in GitHub Desktop.
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