javax.security.cert.X509Certificate Java Examples

The following examples show how to use javax.security.cert.X509Certificate. 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: 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 #2
Source File: ChannelHandlerCallBack.java    From WeCross with Apache License 2.0 6 votes vote down vote up
private PublicKey fetchCertificate(ChannelHandlerContext ctx)
        throws SSLPeerUnverifiedException {
    SslHandler sslhandler = (SslHandler) ctx.channel().pipeline().get(SslHandler.class);

    logger.info(String.valueOf(ctx.channel().pipeline().names()));

    X509Certificate cert = sslhandler.engine().getSession().getPeerCertificateChain()[0];
    PublicKey publicKey = cert.getPublicKey();
    Principal principal = cert.getSubjectDN();

    logger.info(
            " algorithm: {}, format: {}, class name: {}",
            publicKey.getAlgorithm(),
            publicKey.getFormat(),
            publicKey.getClass().getName());
    logger.info(
            " encoded: {}, hex encoded: {}",
            publicKey.getEncoded(),
            bytesToHex(publicKey.getEncoded()));
    logger.info(
            " principal name: {} ,principal class name: {}",
            principal.getName(),
            principal.getClass().getName());

    return publicKey;
}
 
Example #3
Source File: JSSESupport.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public Object[] getPeerCertificateChain(boolean force)
    throws IOException {
    // Look up the current SSLSession
    if (session == null)
        return null;

    // Convert JSSE's certificate format to the ones we need
    X509Certificate [] jsseCerts = null;
    try {
        jsseCerts = session.getPeerCertificateChain();
    } catch(Exception bex) {
        // ignore.
    }
    if (jsseCerts == null)
        jsseCerts = new X509Certificate[0];
    if(jsseCerts.length <= 0 && force && ssl != null) {
        session.invalidate();
        handShake();
        session = ssl.getSession();
    }
    return getX509Certificates(session);
}
 
Example #4
Source File: MutualSSLCertificateHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleRequest(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MsgContext =
            ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map headers =
            (Map) axis2MsgContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    try {
        X509Certificate clientCertificate = Utils.getClientCertificate(axis2MsgContext);
        headers.remove(Utils.getClientCertificateHeader());
        if (clientCertificate != null) {
            byte[] encoded = Base64.encodeBase64(clientCertificate.getEncoded());
            String base64EncodedString =
                    APIConstants.BEGIN_CERTIFICATE_STRING
                            .concat(new String(encoded)).concat("\n")
                            .concat(APIConstants.END_CERTIFICATE_STRING);
            base64EncodedString = Base64.encodeBase64URLSafeString(base64EncodedString.getBytes());
            headers.put(Utils.getClientCertificateHeader(), base64EncodedString);
        }
    } catch (APIManagementException | CertificateEncodingException e) {
        log.error("Error while converting client certificate", e);
    }
    return true;
}
 
Example #5
Source File: MqttTransportHandler.java    From Groza with Apache License 2.0 6 votes vote down vote up
private void processX509CertConnect(ChannelHandlerContext ctx, X509Certificate cert) {
    try {
        String strCert = SslUtil.getX509CertificateString(cert);
        String sha3Hash = EncryptionUtil.getSha3Hash(strCert);
        if (deviceSessionCtx.login(new DeviceX509Credentials(sha3Hash))) {
            ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED));
            connected = true;
            processor.process(new BasicTransportToDeviceSessionActorMsg(deviceSessionCtx.getDevice(),
                    new BasicAdaptorToSessionActorMsg(deviceSessionCtx, new SessionOpenMsg())));
            checkGatewaySession();
        } else {
            ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED));
            ctx.close();
        }
    } catch (Exception e) {
        ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED));
        ctx.close();
    }
}
 
Example #6
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 #7
Source File: TextFileCertificateLoginModuleTest.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private JaasCallbackHandler getJaasCertificateCallbackHandler(String user) {
   JMXPrincipal principal = new JMXPrincipal(user);
   X509Certificate cert = new StubX509Certificate(principal);
   return new JaasCallbackHandler(null, null, null) {
      @Override
      public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
         for (Callback callback : callbacks) {
            if (callback instanceof CertificateCallback) {
               CertificateCallback certCallback = (CertificateCallback) callback;
               certCallback.setCertificates(new X509Certificate[]{cert});
            } else {
               throw new UnsupportedCallbackException(callback);
            }
         }
      }
   };
}
 
Example #8
Source File: Http2SslSessionInfo.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException, RenegotiationRequiredException {
    try {
        return channel.getSslSession().getPeerCertificateChain();
    } catch (SSLPeerUnverifiedException e) {
        try {
            SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE);
            if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) {
                throw new RenegotiationRequiredException();
            }
        } catch (IOException e1) {
            //ignore, will not actually happen
        }
        throw e;
    }
}
 
Example #9
Source File: ConnectionSSLSessionInfo.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException, RenegotiationRequiredException {
    if(unverified != null) {
        throw unverified;
    }
    if(renegotiationRequiredException != null) {
        throw renegotiationRequiredException;
    }
    try {
        return channel.getSslSession().getPeerCertificateChain();
    } catch (SSLPeerUnverifiedException e) {
        try {
            SslClientAuthMode sslClientAuthMode = channel.getOption(Options.SSL_CLIENT_AUTH_MODE);
            if (sslClientAuthMode == SslClientAuthMode.NOT_REQUESTED) {
                renegotiationRequiredException = RENEGOTIATION_REQUIRED_EXCEPTION;
                throw renegotiationRequiredException;
            }
        } catch (IOException e1) {
            //ignore, will not actually happen
        }
        unverified = PEER_UNVERIFIED_EXCEPTION;
        throw unverified;
    }
}
 
Example #10
Source File: MqttTransportHandler.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
private void processX509CertConnect(ChannelHandlerContext ctx, X509Certificate cert, String clientIdentifier) {
  try {
    String strCert = SslUtil.getX509CertificateString(cert);
    String sha3Hash = EncryptionUtil.getSha3Hash(strCert);
    boolean login = deviceSessionCtx.login(new DeviceX509Credentials(sha3Hash));

    if (login) {
      MemoryMetaPool.registerClienId(clientIdentifier, ctx.channel());
      ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED));
      connected = true;
      checkGatewaySession();
    } else {
      ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED));
      ctx.close();
    }
  } catch (Exception e) {
    ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED));
    ctx.close();
  }
}
 
Example #11
Source File: JSSESupport.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public Object[] getPeerCertificateChain(boolean force)
    throws IOException {
    // Look up the current SSLSession
    if (session == null)
        return null;

    // Convert JSSE's certificate format to the ones we need
    X509Certificate [] jsseCerts = null;
    try {
        jsseCerts = session.getPeerCertificateChain();
    } catch(Exception bex) {
        // ignore.
    }
    if (jsseCerts == null)
        jsseCerts = new X509Certificate[0];
    if(jsseCerts.length <= 0 && force && ssl != null) {
        session.invalidate();
        handShake();
        session = ssl.getSession();
    }
    return getX509Certificates(session);
}
 
Example #12
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 #13
Source File: VertxHttpFacade.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain() {
    try {
        return routingContext.request().peerCertificateChain();
    } catch (SSLPeerUnverifiedException e) {
        throw new RuntimeException("Failed to fetch certificates from request", e);
    }
}
 
Example #14
Source File: SslClientCertAttribute.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static String toPem(final X509Certificate certificate) throws CertificateEncodingException {
    final StringBuilder builder = new StringBuilder();
    builder.append(BEGIN_CERT);
    builder.append('\n');
    builder.append(Base64.getEncoder().encodeToString(certificate.getEncoded()));
    builder.append('\n');
    builder.append(END_CERT);
    return builder.toString();
}
 
Example #15
Source File: Certificates.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
public static String toPem(final X509Certificate certificate) throws CertificateEncodingException {
    final StringBuilder builder = new StringBuilder();
    builder.append(BEGIN_CERT);
    builder.append('\n');
    builder.append(FlexBase64.encodeString(certificate.getEncoded(), true));
    builder.append('\n');
    builder.append(END_CERT);
    return builder.toString();
}
 
Example #16
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 #17
Source File: OcspClientExample.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean verify(ChannelHandlerContext ctx, ReferenceCountedOpenSslEngine engine) throws Exception {
    byte[] staple = engine.getOcspResponse();
    if (staple == null) {
        throw new IllegalStateException("Server didn't provide an OCSP staple!");
    }

    OCSPResp response = new OCSPResp(staple);
    if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) {
        return false;
    }

    SSLSession session = engine.getSession();
    X509Certificate[] chain = session.getPeerCertificateChain();
    BigInteger certSerial = chain[0].getSerialNumber();

    BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject();
    SingleResp first = basicResponse.getResponses()[0];

    // ATTENTION: CertificateStatus.GOOD is actually a null value! Do not use
    // equals() or you'll NPE!
    CertificateStatus status = first.getCertStatus();
    BigInteger ocspSerial = first.getCertID().getSerialNumber();
    String message = new StringBuilder()
        .append("OCSP status of ").append(ctx.channel().remoteAddress())
        .append("\n  Status: ").append(status == CertificateStatus.GOOD ? "Good" : status)
        .append("\n  This Update: ").append(first.getThisUpdate())
        .append("\n  Next Update: ").append(first.getNextUpdate())
        .append("\n  Cert Serial: ").append(certSerial)
        .append("\n  OCSP Serial: ").append(ocspSerial)
        .toString();
    System.out.println(message);

    return status == CertificateStatus.GOOD && certSerial.equals(ocspSerial);
}
 
Example #18
Source File: BasicSSLSessionInfo.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if (certificate == null) {
        throw UndertowMessages.MESSAGES.peerUnverified();
    }
    return certificate;
}
 
Example #19
Source File: OpenSSlSession.java    From wildfly-openssl with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if (x509PeerCerts == null) {
        throw new SSLPeerUnverifiedException(Messages.MESSAGES.unverifiedPeer());
    }
    return x509PeerCerts;
}
 
Example #20
Source File: Certificates.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static String toPem(final X509Certificate certificate) throws CertificateEncodingException {
    final StringBuilder builder = new StringBuilder();
    builder.append(BEGIN_CERT);
    builder.append('\n');
    builder.append(FlexBase64.encodeString(certificate.getEncoded(), true));
    builder.append('\n');
    builder.append(END_CERT);
    return builder.toString();
}
 
Example #21
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 #22
Source File: PolicyEnforcerClaimsTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private OIDCHttpFacade createHttpFacade(String path, String method, String token, Map<String, List<String>> headers, Map<String, List<String>> parameters, InputStream requestBody) {
    return new OIDCHttpFacade() {
        Request request;
        Response response;

        @Override
        public KeycloakSecurityContext getSecurityContext() {
            AccessToken accessToken;
            try {
                accessToken = new JWSInput(token).readJsonContent(AccessToken.class);
            } catch (JWSInputException cause) {
                throw new RuntimeException(cause);
            }
            return new KeycloakSecurityContext(token, accessToken, null, null);
        }

        @Override
        public Request getRequest() {
            if (request == null) {
                request = createHttpRequest(path, method, headers, parameters, requestBody);
            }
            return request;
        }

        @Override
        public Response getResponse() {
            if (response == null) {
                response = createHttpResponse(headers);
            }
            return response;
        }

        @Override
        public X509Certificate[] getCertificateChain() {
            return new X509Certificate[0];
        }
    };
}
 
Example #23
Source File: CertificateLoginModule.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected String getDistinguishedName(final X509Certificate[] certs) {
   if (certs != null && certs.length > 0 && certs[0] != null) {
      return certs[0].getSubjectDN().getName();
   } else {
      return null;
   }
}
 
Example #24
Source File: SslHandshakeInfo.java    From zuul with Apache License 2.0 5 votes vote down vote up
public SslHandshakeInfo(boolean isOfIntermediary, String protocol, String cipherSuite, ClientAuth clientAuthRequirement,
                        Certificate serverCertificate, X509Certificate clientCertificate)
{
    this.protocol = protocol;
    this.cipherSuite = cipherSuite;
    this.clientAuthRequirement = clientAuthRequirement;
    this.serverCertificate = serverCertificate;
    this.clientCertificate = clientCertificate;
    this.isOfIntermediary = isOfIntermediary;
}
 
Example #25
Source File: CertificateUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static X509Certificate[] getCertsFromConnection(RemotingConnection remotingConnection) {
   X509Certificate[] certificates = null;
   if (remotingConnection != null) {
      Connection transportConnection = remotingConnection.getTransportConnection();
      if (transportConnection instanceof NettyConnection) {
         certificates = org.apache.activemq.artemis.utils.CertificateUtil.getCertsFromChannel(((NettyConnection) transportConnection).getChannel());
      }
   }
   return certificates;
}
 
Example #26
Source File: CertificateUtil.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public static X509Certificate[] getCertsFromChannel(Channel channel) {
   X509Certificate[] certificates = null;
   ChannelHandler channelHandler = channel.pipeline().get("ssl");
   if (channelHandler != null && channelHandler instanceof SslHandler) {
      SslHandler sslHandler = (SslHandler) channelHandler;
      try {
         certificates = sslHandler.engine().getSession().getPeerCertificateChain();
      } catch (SSLPeerUnverifiedException e) {
         // ignore
      }
   }

   return certificates;
}
 
Example #27
Source File: TestUtils.java    From vertx-codegen with Apache License 2.0 5 votes vote down vote up
public static String cnOf(X509Certificate cert) throws Exception {
  String dn = cert.getSubjectDN().getName();
  LdapName ldapDN = new LdapName(dn);
  for (Rdn rdn : ldapDN.getRdns()) {
    if (rdn.getType().equalsIgnoreCase("cn")) {
      return rdn.getValue().toString();
    }
  }
  return null;
}
 
Example #28
Source File: MutualSSLAuthenticator.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationResponse authenticate(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();
    // try to retrieve the certificate
    X509Certificate sslCertObject;
    try {
        sslCertObject = Utils.getClientCertificate(axis2MessageContext);
    } catch (APIManagementException e) {
        return new AuthenticationResponse(false, isMandatory, !isMandatory,
                APISecurityConstants.API_AUTH_GENERAL_ERROR, e.getMessage());
    }

    /* If the certificate cannot be retrieved from the axis2Message context, then mutual SSL authentication has
     not happened in transport level.*/
    if (sslCertObject == null) {
        if (log.isDebugEnabled()) {
            log.debug("Mutual SSL authentication has not happened in the transport level for the API "
                    + getAPIIdentifier(messageContext).toString() + ", hence API invocation is not allowed");
        }
        if (isMandatory) {
            log.error("Mutual SSL authentication failure");
        }
        return new AuthenticationResponse(false, isMandatory, !isMandatory,
                APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
    } else {
        try {
            setAuthContext(messageContext, sslCertObject);
        } catch (APISecurityException ex) {
            return new AuthenticationResponse(false, isMandatory, !isMandatory, ex.getErrorCode(), ex.getMessage());
        }
    }
    return new AuthenticationResponse(true, isMandatory, true, 0, null);
}
 
Example #29
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 #30
Source File: mySSLSession.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if(xCerts == null) {
        throw new SSLPeerUnverifiedException("peer not authenticated");
    } else {
        return xCerts;
    }
}