Skip to content

Instantly share code, notes, and snippets.

@arax
Last active December 12, 2015 06:39
Show Gist options
  • Save arax/4731144 to your computer and use it in GitHub Desktop.
Save arax/4731144 to your computer and use it in GitHub Desktop.
Reading PKCS#12 credentials in jRuby using Java's java.security.KeyStore
require 'java'
require 'highline/import'
keystore = Java::JavaSecurity::KeyStore.getInstance("PKCS12")
path = ask "Enter full path to the PKCS#12 file: "
fis = Java::JavaIo::FileInputStream.new(path)
password = ask("Enter you PKCS#12 password: ") { |q| q.echo = false }
password = Java::JavaLang::String.new(password).to_char_array
puts "Loading KeyStore ..."
keystore.load(fis, password)
puts "Looking for aliases ..."
keystore.aliases().each do |keystore_alias|
puts "\tAlias: " + keystore_alias
end
puts "KeyStore type: " + keystore.type
puts "KeyStore provider: " + keystore.provider.inspect
puts "Number of entries in this KeyStore: " + keystore.size.to_s
puts "\n#################################################################\n"
puts "Printing the first certificate and key ..."
puts cert = keystore.getCertificate("1")
puts pk = keystore.getKey("1", password)
puts "\n#################################################################\n"
cert_base64 = "-----BEGIN CERTIFICATE-----\n"
cert_base64 << Java::JavaxXmlBind::DatatypeConverter.printBase64Binary(cert.getEncoded())
cert_base64 << "\n-----END CERTIFICATE-----"
pk_base64 = "-----BEGIN PRIVATE KEY-----\n"
pk_base64 << Java::JavaxXmlBind::DatatypeConverter.printBase64Binary(pk.getEncoded())
pk_base64 << "\n-----END PRIVATE KEY-----"
puts "Printing the first certificate and key in Base64 ..."
puts cert_base64
puts pk_base64
puts "\n#################################################################\n"
puts "PK encoded using: " + pk.getFormat()
@arax
Copy link
Author

arax commented Feb 7, 2013

cert.getEncoded() will output ASN.1 DER encoded byte array
pk.getEncoded() will output PKCS#8 encoded byte array

Notice: There is no RSA in "-----BEGIN PRIVATE KEY-----"!

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