Java Code Examples for javax.security.cert.X509Certificate#getInstance()

The following examples show how to use javax.security.cert.X509Certificate#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertificateUtils.java    From product-microgateway with Apache License 2.0 6 votes vote down vote up
public static String getAliasFromHeaderCert(String base64EncodedCertificate) {
    try {
        base64EncodedCertificate = URLDecoder.decode(base64EncodedCertificate).
                replaceAll(Constants.BEGIN_CERTIFICATE_STRING, "").replaceAll(Constants.END_CERTIFICATE_STRING, "");
        byte[] bytes = Base64.decodeBase64(base64EncodedCertificate);
        InputStream inputStream = new ByteArrayInputStream(bytes);
        X509Certificate x509Certificate = X509Certificate.getInstance(inputStream);
        if (getAliasFromTrustStore(x509Certificate, LoadKeyStore.trustStore) != null) {
            return getAliasFromTrustStore(x509Certificate, LoadKeyStore.trustStore);
        }
        return "";
    } catch (KeyStoreException | java.security.cert.CertificateException | CertificateException e) {
        String msg = "Error while decoding certificate present in the header and validating with the trust store.";
        log.error(msg, e);
        throw ErrorUtils.getBallerinaError(msg, e);
    }
}
 
Example 2
Source File: AuthenticationHandlerTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Handle request with device type URI with Mutual Auth Header",
        dependsOnMethods = "testHandleSuccessRequestProxyMutualAuthHeader")
public void testHandleSuccessRequestMutualAuthHeader() throws Exception {
    HashMap<String, String> transportHeaders = new HashMap<>();
    transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
    setMockClient();
    this.mockClient.setResponse(getAccessTokenReponse());
    this.mockClient.setResponse(getValidationResponse());
    MessageContext messageContext = createSynapseMessageContext("<empty/>", this.synapseConfiguration,
            transportHeaders, "https://test.com/testservice/api/testdevice");
    org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    String certStr = getContent(TestUtils.getAbsolutePathOfConfig("ra_cert.pem"));
    X509Certificate cert = X509Certificate.getInstance(new ByteArrayInputStream(certStr.
            getBytes(StandardCharsets.UTF_8.name())));
    axisMC.setProperty(AuthConstants.CLIENT_CERTIFICATE, new X509Certificate[]{cert});
    boolean response = this.handler.handleRequest(messageContext);
    Assert.assertTrue(response);
    this.mockClient.reset();
}
 
Example 3
Source File: OpenSslEngine.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    // these are lazy created to reduce memory overhead
    X509Certificate[] c = x509PeerCerts;
    if (c == null) {
        if (SSL.isInInit(ssl) != 0) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        byte[][] chain = SSL.getPeerCertChain(ssl);
        if (chain == null) {
            throw new SSLPeerUnverifiedException("peer not verified");
        }
        X509Certificate[] peerCerts = new X509Certificate[chain.length];
        for (int i = 0; i < peerCerts.length; i++) {
            try {
                peerCerts[i] = X509Certificate.getInstance(chain[i]);
            } catch (CertificateException e) {
                throw new IllegalStateException(e);
            }
        }
        c = x509PeerCerts = peerCerts;
    }
    return c;
}
 
Example 4
Source File: OpenSslJavaxX509Certificate.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private X509Certificate unwrap() {
    X509Certificate wrapped = this.wrapped;
    if (wrapped == null) {
        try {
            wrapped = this.wrapped = X509Certificate.getInstance(bytes);
        } catch (CertificateException e) {
            throw new IllegalStateException(e);
        }
    }
    return wrapped;
}
 
Example 5
Source File: WxCommonUtil.java    From roncoo-pay with Apache License 2.0 5 votes vote down vote up
/**
 * @param content    对敏感内容(入参Content)加密
 * @param ciphertext 平台证书接口得到的参数certificates包含了加密的平台证书内容ciphertext
 * @return
 * @throws Exception
 */
public static String rsaEncrypt(String content, String ciphertext) throws Exception {
    final byte[] PublicKeyBytes = ciphertext.getBytes();
    X509Certificate certificate = X509Certificate.getInstance(PublicKeyBytes);
    PublicKey publicKey = certificate.getPublicKey();
    Cipher ci = Cipher.getInstance("RSA/ECB/PKCS1Padding", "SunJCE");
    ci.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encode(ci.doFinal(content.getBytes("UTF-8")));
}
 
Example 6
Source File: mySSLSession.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public mySSLSession(Certificate[] xc) throws CertificateEncodingException, CertificateException {
    certs = xc;
    xCerts = new X509Certificate[xc.length];
    int i = 0;
    for (Certificate cert : xc) {
        xCerts[i++] = X509Certificate.getInstance(cert.getEncoded());
    }
}
 
Example 7
Source File: CertInfo.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
public CertInfo(String certPath) {
    try {
        FileInputStream file = new FileInputStream(certPath);
        X509Certificate cert = X509Certificate.getInstance(file);
        this.certs = new X509Certificate[]{cert};
    } catch(FileNotFoundException|CertificateException e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example 8
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Scenario:
 *   - Select client key alias `gateway2`.
 *   - Mutual trust exists between gateway and API
 *   - We must use the `gateway2` cert NOT `gateway`.
 * @throws CertificateException the certificate exception
 * @throws IOException the IO exception
 */
@Test
public void shouldSucceedWhenValidKeyAlias() throws CertificateException, IOException  {
    config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ts.jks"));
    config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ks.jks"));
    config.put(TLSOptions.TLS_KEYSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYPASSWORD, "password");
    config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
    config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");

    config.put(TLSOptions.TLS_KEYALIASES, "gateway2");

    InputStream inStream = new FileInputStream(getResourcePath("2waytest/basic_mutual_auth_2/gateway2.cer"));
    final X509Certificate expectedCert = X509Certificate.getInstance(inStream);
    inStream.close();

    HttpConnectorFactory factory = new HttpConnectorFactory(config);
    IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.MTLS, false, new ConnectorConfigImpl());
    IApiConnection connection = connector.connect(request,
            new IAsyncResultHandler<IApiConnectionResponse>() {

                @Override
                public void handle(IAsyncResult<IApiConnectionResponse> result) {
                    if (result.isError())
                        throw new RuntimeException(result.getError());

                    Assert.assertTrue(result.isSuccess());
                    // Assert that the expected certificate (associated with the private key by virtue)
                    // was the one used.
                    Assert.assertEquals(expectedCert.getSerialNumber(), clientSerial);
                }
            });

    connection.end();
}
 
Example 9
Source File: BasicMutualAuthTest.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Scenario:
 *   - First alias invalid, second valid.
 *   - Mutual trust exists between gateway and API.
 *   - We must fall back to the valid alias.
 * @throws CertificateException the certificate exception
 * @throws IOException the IO exception
 */
@Test
public void shouldFallbackWhenMultipleAliasesAvailable() throws CertificateException, IOException  {
    config.put(TLSOptions.TLS_TRUSTSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ts.jks"));
    config.put(TLSOptions.TLS_TRUSTSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYSTORE, getResourcePath("2waytest/basic_mutual_auth_2/gateway_ks.jks"));
    config.put(TLSOptions.TLS_KEYSTOREPASSWORD, "password");
    config.put(TLSOptions.TLS_KEYPASSWORD, "password");
    config.put(TLSOptions.TLS_ALLOWANYHOST, "true");
    config.put(TLSOptions.TLS_ALLOWSELFSIGNED, "false");
    // Only gateway2 is valid. `unrelated` is real but not trusted by API. others don't exist.
    config.put(TLSOptions.TLS_KEYALIASES, "unrelated, owt, or, nowt, gateway2, sonorous, unrelated");

    InputStream inStream = new FileInputStream(getResourcePath("2waytest/basic_mutual_auth_2/gateway2.cer"));
    final X509Certificate expectedCert = X509Certificate.getInstance(inStream);
    inStream.close();

    HttpConnectorFactory factory = new HttpConnectorFactory(config);
    IApiConnector connector = factory.createConnector(request, api, RequiredAuthType.MTLS, false, new ConnectorConfigImpl());
    IApiConnection connection = connector.connect(request,
            new IAsyncResultHandler<IApiConnectionResponse>() {

                @Override
                public void handle(IAsyncResult<IApiConnectionResponse> result) {
                    if (result.isError())
                        throw new RuntimeException(result.getError());

                    Assert.assertTrue(result.isSuccess());
                    // Assert that the expected certificate (associated with the private key by virtue)
                    // was the one used.
                    Assert.assertEquals(expectedCert.getSerialNumber(), clientSerial);
                }
            });

    connection.end();
}