Last active
December 12, 2015 06:39
-
-
Save arax/4731144 to your computer and use it in GitHub Desktop.
Reading PKCS#12 credentials in jRuby using Java's java.security.KeyStore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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-----"!