Created
April 9, 2017 22:49
-
-
Save film42/b700340f43a8a6153231b84c91d82a5a to your computer and use it in GitHub Desktop.
Load a x509 cert + rsa key and x509 ca and create an sslcontext in java using jruby. This took me a few hours to figure out since I wasn't super familiar with java, but here you go! Btw, you'll notice I'm using bouncycastle which is fine because it's a dependency of jruby-openssl. So as long as you require "openssl" this should work out of the box.
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 "openssl" | |
def create_ssl_context(options) | |
# Create our certs and key converters to go from bouncycastle to java. | |
cert_converter = org.bouncycastle.cert.jcajce.JcaX509CertificateConverter.new | |
key_converter = org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter.new | |
# Load the certs and keys. | |
tls_ca_cert = cert_converter.getCertificate(read_pem_object_from_file(options[:tls_ca_cert])) | |
tls_client_cert = cert_converter.getCertificate(read_pem_object_from_file(options[:tls_client_cert])) | |
tls_client_key = key_converter.getKeyPair(read_pem_object_from_file(options[:tls_client_key])) | |
# Setup the CA cert. | |
ca_key_store = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType) | |
ca_key_store.load(nil, nil) | |
ca_key_store.setCertificateEntry("ca-certificate", tls_ca_cert) | |
trust_manager = javax.net.ssl.TrustManagerFactory.getInstance(javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm) | |
trust_manager.init(ca_key_store) | |
# Setup the cert / key pair. | |
client_key_store = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType) | |
client_key_store.load(nil, nil) | |
client_key_store.setCertificateEntry("certificate", tls_client_cert) | |
certificate_java_array = [tls_client_cert].to_java(java.security.cert.Certificate) | |
empty_password = [].to_java(:char) | |
client_key_store.setKeyEntry("private-key", tls_client_key.getPrivate, empty_password, certificate_java_array) | |
key_manager = javax.net.ssl.KeyManagerFactory.getInstance(javax.net.ssl.KeyManagerFactory.getDefaultAlgorithm) | |
key_manager.init(client_key_store, empty_password) | |
# Create ssl context. | |
context = javax.net.ssl.SSLContext.getInstance("TLSv1.2") | |
context.init(key_manager.getKeyManagers, trust_manager.getTrustManagers, nil) | |
context | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment