Created
August 27, 2020 16:19
-
-
Save GrakovNe/2c8637c2f9e8ccbbba63a2c8088bf2da to your computer and use it in GitHub Desktop.
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
| import java.io.ByteArrayInputStream; | |
| import java.io.IOException; | |
| import java.security.KeyStore; | |
| import java.security.KeyStoreException; | |
| import java.security.NoSuchAlgorithmException; | |
| import java.security.SecureRandom; | |
| import java.security.cert.CertificateException; | |
| import java.security.cert.CertificateFactory; | |
| import java.security.cert.X509Certificate; | |
| import javax.net.ssl.SSLContext; | |
| import javax.net.ssl.TrustManagerFactory; | |
| import org.jetbrains.annotations.NotNull; | |
| public class Test { | |
| public SSLContext provideSecureContext(String pem) throws Exception { | |
| var x509Certificate = buildX509FromPem(pem.getBytes()); | |
| KeyStore keyStore = initKeystore(x509Certificate); | |
| return buildSslContext(keyStore); | |
| } | |
| public static SSLContext buildSslContext(KeyStore keyStore) throws Exception { | |
| TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | |
| factory.init(keyStore); | |
| SSLContext context = SSLContext.getInstance("TLS"); | |
| context.init(null, factory.getTrustManagers(), new SecureRandom()); | |
| return context; | |
| } | |
| @NotNull | |
| public static KeyStore initKeystore(X509Certificate pempem) throws Exception { | |
| KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); | |
| keyStore.load(null, null); | |
| keyStore.setCertificateEntry(Integer.toString(1), pempem); | |
| return keyStore; | |
| } | |
| protected static X509Certificate buildX509FromPem(byte[] certBytes) throws CertificateException { | |
| CertificateFactory factory = CertificateFactory.getInstance("X.509"); | |
| return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment