Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.casbah.provider.openssl.OpenSslCAProvider.java

private X509Certificate getCertificate(File certFile) throws CertificateException, FileNotFoundException {
    FileInputStream fis = new FileInputStream(certFile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    return (X509Certificate) cf.generateCertificate(fis);
}

From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java

public X509Certificate generateV1Certificate(String subject, char[] ksPass, KeyStore keyStore)
        throws OperatorCreationException, IOException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException {
    KeyPair pair = generateKeyPair();

    BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis());
    X500Name issuerDN = new X500Name("CN=" + subject);
    X500Name subjectDN = new X500Name("CN=" + subject);
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(System.currentTimeMillis() + 10000);
    PublicKey pubKey = (pair.getPublic());
    X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore,
            notAfter, subjectDN, pubKey);

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").build(pair.getPrivate());
    byte[] encoded = certGen.build(signer).getEncoded();
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    InputStream is = new ByteArrayInputStream(encoded);
    X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is);
    is.close();// w  w  w.  j  a v a  2s . co m

    // set the CA cert as trusted root
    X509Certificate[] chain = new X509Certificate[] { generateCertificate };
    addToKeyStore(pair, chain, K_NAME, keyStore, ksPass);

    String certStr = generateCertificate.toString();

    return generateCertificate;
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public X509Certificate getCertificate() {

    try {/*w  w  w . j  a v  a 2s  .  com*/
        //Extract the x.509 certificates
        InputStream inStream = new FileInputStream(_Pathway + _Certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        _Certificate = null;
        return cert;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:org.hyperledger.fabric.sdk.MemberServicesImpl.java

/**
 * Process a batch of tcerts after having retrieved them from the TCA.
 *//*from w w  w . jav  a 2s .c om*/
private List<TCert> processTCertBatch(GetTCertBatchRequest req, TCertCreateSetResp resp)
        throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException, CryptoException, IOException {
    String enrollKey = req.getEnrollment().getKey();
    byte[] tCertOwnerKDFKey = resp.getCerts().getKey().toByteArray();
    List<Ca.TCert> tCerts = resp.getCerts().getCertsList();

    byte[] byte1 = new byte[] { 1 };
    byte[] byte2 = new byte[] { 2 };

    byte[] tCertOwnerEncryptKey = Arrays.copyOfRange(cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte1), 0,
            32);
    byte[] expansionKey = cryptoPrimitives.calculateMac(tCertOwnerKDFKey, byte2);

    List<TCert> tCertBatch = new ArrayList<>(tCerts.size());

    // Loop through certs and extract private keys
    for (Ca.TCert tCert : tCerts) {
        X509Certificate x509Certificate;
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            x509Certificate = (X509Certificate) cf.generateCertificate(tCert.getCert().newInput());
        } catch (Exception ex) {
            logger.debug("Warning: problem parsing certificate bytes; retrying ... ", ex);
            continue;
        }

        // extract the encrypted bytes from extension attribute
        byte[] tCertIndexCT = fromDer(x509Certificate.getExtensionValue(TCERT_ENC_TCERT_INDEX));
        byte[] tCertIndex = cryptoPrimitives.aesCBCPKCS7Decrypt(tCertOwnerEncryptKey, tCertIndexCT);

        byte[] expansionValue = cryptoPrimitives.calculateMac(expansionKey, tCertIndex);

        // compute the private key
        BigInteger k = new BigInteger(1, expansionValue);
        BigInteger n = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey)))
                .getParameters().getN().subtract(BigInteger.ONE);
        k = k.mod(n).add(BigInteger.ONE);

        BigInteger D = ((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getD()
                .add(k);
        D = D.mod(((ECPrivateKey) cryptoPrimitives.ecdsaKeyFromPrivate(Hex.decode(enrollKey))).getParameters()
                .getN());

        // Put private and public key in returned tcert
        TCert tcert = new TCert(tCert.getCert().toByteArray(), cryptoPrimitives.ecdsaKeyFromBigInt(D));

        tCertBatch.add(tcert);
    }

    if (tCertBatch.size() == 0) {
        throw new RuntimeException("Failed fetching TCertBatch. No valid TCert received.");
    }

    return tCertBatch;
}

From source file:be.solidx.hot.nio.HttpsClient.java

private TrustManager[] handleTrustManagers(Map<String, Object> options)
        throws CertificateException, IOException, URISyntaxException {
    boolean rejectUnauthorized = (boolean) options.get(REJECTUNAUTHORIZED);
    if (options.get(CA) != null) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(
                (X509Certificate) certificateFactory
                        .generateCertificate(getInputStream(new URI(options.get(CA).toString()))),
                rejectUnauthorized) };//from w w  w . jav a2  s .  c om
    } else if (!rejectUnauthorized) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return new TrustManager[] { new TrustManager(null, rejectUnauthorized) };
    }
    return null;
}

From source file:ddf.security.samlp.SimpleSign.java

public boolean validateSignature(String sigAlg, String queryParamsToValidate, String encodedSignature,
        @Nullable String encodedPublicKey) throws SignatureException {
    if (encodedPublicKey == null) {
        LOGGER.warn(//from ww w.  j a v  a 2s .c  o  m
                "Could not verify the signature of request because there was no signing certificate. Ensure that the IdP Metadata includes a signing certificate.");
        return false;
    }

    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory.generateCertificate(
                new ByteArrayInputStream(Base64.getMimeDecoder().decode(encodedPublicKey)));

        java.security.Signature sig;
        String jceSigAlg = JCEMapper.translateURItoJCEID(sigAlg);

        if (jceSigAlg == null) {
            throw new SignatureException(new NoSuchAlgorithmException(
                    String.format("The Signature Algorithm %s is not supported.", sigAlg)));
        }

        try {
            sig = java.security.Signature.getInstance(jceSigAlg);
        } catch (NoSuchAlgorithmException e) {
            throw new SignatureException(e);
        }

        sig.initVerify(certificate.getPublicKey());
        sig.update(queryParamsToValidate.getBytes(StandardCharsets.UTF_8));
        return sig.verify(Base64.getMimeDecoder().decode(encodedSignature));
    } catch (InvalidKeyException | CertificateException | java.security.SignatureException
            | IllegalArgumentException e) {
        throw new SignatureException(e);
    }
}

From source file:org.sinekartads.smartcard.SmartCardAccess.java

private X509Certificate toX509Certificate(X509PublicKeyCertificate iaikCert) throws SmartCardAccessException {
    CertificateFactory cf;
    try {//w  w w.j av  a 2s.  c o m
        cf = CertificateFactory.getInstance("X.509");
        return (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(iaikCert.getValue().getByteArrayValue()));
    } catch (CertificateException e) {
        tracer.error("Generic error on toX509Certificate", e);
        throw new SmartCardAccessException("Generic error on toX509Certificate", e);
    }
}

From source file:be.fedict.trust.xkms2.XKMSPortImpl.java

private X509Certificate getCertificate(byte[] encodedCertificate) throws CertificateException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN.//  w  w w  . jav a 2  s  .  c  o  m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (LOG.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:org.wso2.carbon.apimgt.handlers.AuthenticationHandler.java

/**
 * Handling the message and checking the security.
 *
 * @param messageContext Request message context.
 * @return Boolean value of the result of the processing the request.
 *///  w  w  w.j  a va 2 s.  c  om
@Override
public boolean handleRequest(org.apache.synapse.MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axisMC = ((Axis2MessageContext) messageContext)
            .getAxis2MessageContext();

    String ctxPath = messageContext.getTo().getAddress().trim();

    if (log.isDebugEnabled()) {
        log.debug("Authentication handler invoked by: " + ctxPath);
    }
    Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS);
    try {
        int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
        RESTResponse response = null;
        if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) {

            String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE);
            if (log.isDebugEnabled()) {
                log.debug("Verify Cert:\n" + mdmSignature);
            }
            String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
            if (deviceType == null) {
                return false;
            }
            URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
            Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);

            Certificate certificate = new Certificate();
            certificate.setPem(mdmSignature);
            certificate.setTenantId(tenantId);
            certificate.setSerial("");

            Gson gson = new Gson();
            String certVerifyContent = gson.toJson(certificate);
            response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);

            String str = response.getContent();
            if (log.isDebugEnabled()) {
                log.debug("Verify response:" + response.getContent());
                log.debug("Response String : " + str);
            }
            if (response.getHttpStatus() == 200 && str.contains(JWTTOKEN)) {
                ValidationResponce validationResponce = gson.fromJson(str, ValidationResponce.class);
                headers.put(X_JWT_ASSERTION, validationResponce.getJWTToken());
            } else {
                return false;
            }

        } else if (headers.containsKey(AuthConstants.PROXY_MUTUAL_AUTH_HEADER)) {
            String subjectDN = headers.get(AuthConstants.PROXY_MUTUAL_AUTH_HEADER);

            if (log.isDebugEnabled()) {
                log.debug("Verify subject DN: " + subjectDN);
            }

            String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
            URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
            Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);
            Certificate certificate = new Certificate();
            certificate.setPem(subjectDN);
            certificate.setTenantId(tenantId);
            certificate.setSerial(AuthConstants.PROXY_MUTUAL_AUTH_HEADER);

            Gson gson = new Gson();
            String certVerifyContent = gson.toJson(certificate);
            response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
            if (log.isDebugEnabled()) {
                log.debug("Verify response:" + response.getContent());
            }
        } else if (headers.containsKey(AuthConstants.MUTUAL_AUTH_HEADER)) {
            javax.security.cert.X509Certificate[] certs = (javax.security.cert.X509Certificate[]) axisMC
                    .getProperty(AuthConstants.CLIENT_CERTIFICATE);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded());
            X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            if (x509 != null) {
                headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509));
                return true;
            }
        } else if (headers.containsKey(AuthConstants.ENCODED_PEM)) {
            String encodedPem = headers.get(AuthConstants.ENCODED_PEM);
            if (log.isDebugEnabled()) {
                log.debug("Verify Cert:\n" + encodedPem);
            }
            String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
            URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
            Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);

            Certificate certificate = new Certificate();
            certificate.setPem(encodedPem);
            certificate.setTenantId(tenantId);
            certificate.setSerial("");
            Gson gson = new Gson();
            String certVerifyContent = gson.toJson(certificate);
            response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
            if (log.isDebugEnabled()) {
                log.debug("Verify response:" + response.getContent());
            }
        } else {
            log.warn("Unauthorized request for api: " + ctxPath);
            return false;
        }
        if (response != null && !response.getContent().contains("invalid")) {
            return true;
        }
        log.warn("Unauthorized request for api: " + ctxPath);
        return false;
    } catch (IOException e) {
        log.error("Error while processing certificate.", e);
        return false;
    } catch (URISyntaxException e) {
        log.error("Error while processing certificate.", e);
        return false;
    } catch (APIMCertificateMGTException e) {
        log.error("Error while processing certificate.", e);
        return false;
    } catch (CertificateException e) {
        log.error("Certificate issue occurred when generating converting PEM to x509Certificate", e);
        return false;
    } catch (CertificateEncodingException e) {
        log.error("Error while attempting to encode certificate.", e);
        return false;
    }
}