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:be.fedict.trust.service.bean.TrustDomainServiceBean.java

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

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

From source file:eu.eidas.auth.engine.core.impl.SignP12.java

/**
 * Validate signature.//from w w w  . j  a va  2  s .co  m
 * 
 * @param tokenSaml token SAML
 * 
 * @return the SAMLObject validated.
 * 
 * @throws SAMLEngineException error validate signature
 * 
 */
public SAMLObject validateSignature(final SignableSAMLObject tokenSaml, String messageFormat)
        throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        validateProfileSignature(tokenSaml);

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = trustStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) trustStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        // Validate trust certificates
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();
        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate it is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        LOG.info("Key algorithm {}",
                SecurityHelper.getKeyAlgorithmFromURI(tokenSaml.getSignature().getSignatureAlgorithm()));
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.info("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    return tokenSaml;
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

private void generateCertificate() {
    X500Name name = new X500Name(this.name);
    BigInteger serial = BigInteger.valueOf(1);
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo
            .getInstance(this.keyPair.getPublic().getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(name, serial,
            this.notBefore, this.notAfter, name, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter;
    try {//from  w  ww .ja  v a 2 s.  c  o  m
        asymmetricKeyParameter = PrivateKeyFactory.createKey(this.keyPair.getPrivate().getEncoded());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    ContentSigner contentSigner;
    try {
        contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(asymmetricKeyParameter);
    } catch (OperatorCreationException e) {
        throw new RuntimeException(e);
    }
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate;
    try {
        encodedCertificate = x509CertificateHolder.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * //from   w  w w.  j a  va2s.c o  m
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CertificateDAO.java

/**
 * convert result set to an array of publicCertificates
 *
 * @param resultSet resultSet/*from  w ww.j  a v a 2s.  com*/
 * @return an Array of PublicCertificates
 */
private Certificate[] getCertificateArray(ResultSet resultSet) {
    ArrayList<Certificate> pcList = new ArrayList<Certificate>();
    int count = 0;
    try {
        while (resultSet.next()) {
            Certificate cert = null;
            String serialNo = resultSet.getString(Constants.SERIAL_NO_LABEL);
            String status = resultSet.getString(Constants.PC_STATUS_LABEL);
            Date expiryDate = resultSet.getTimestamp(Constants.PC_EXPIRY_DATE);

            Blob pcBlob = resultSet.getBlob(Constants.PC_CONTENT_LABEL);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            X509Certificate certificate = (X509Certificate) certificateFactory
                    .generateCertificate(pcBlob.getBinaryStream());
            Date issuedDate = resultSet.getTimestamp(Constants.PC_ISSUDED_DATE);
            String username = resultSet.getString(Constants.PC_ISSUER_LABEL);
            int tenantID = resultSet.getInt(Constants.TENANT_ID_LABEL);
            String userStoreDomain = resultSet.getString(Constants.USER_STORE_DOMAIN_LABEL);
            cert = new Certificate(serialNo, certificate, status, tenantID, username, issuedDate, expiryDate,
                    userStoreDomain);
            pcList.add(cert);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    Certificate[] pcFiles = new Certificate[pcList.size()];
    pcFiles = pcList.toArray(pcFiles);
    return pcFiles;
}

From source file:org.eclipse.emf.emfstore.client.model.connectionmanager.KeyStoreManager.java

/**
 * Adds a certificate to the KeyStore.// w  ww . j a va2s . c  o m
 * 
 * @param alias
 *            alias for the certificate
 * @param certificate
 *            inputstream delivering the certificate. Stream is used by
 *            {@link CertificateFactory#generateCertificate(InputStream)}.
 * @throws InvalidCertificateException
 *             certificate cannot be found, accessed or identified
 * @throws CertificateStoreException
 *             is thrown when problems occur with the CertificateStore, i.e.
 *             illegal operations
 */
public void addCertificate(String alias, InputStream certificate)
        throws InvalidCertificateException, CertificateStoreException {
    if (!isDefaultCertificate(alias)) {
        loadKeyStore();
        try {
            CertificateFactory factory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
            Certificate newCertificate = factory.generateCertificate(certificate);
            keyStore.setCertificateEntry(alias, newCertificate);
            storeKeyStore();
        } catch (CertificateException e) {
            String message = "Please choose a valid certificate!";
            throw new InvalidCertificateException(message);
        } catch (KeyStoreException e) {
            String message = "Storing certificate failed!";
            WorkspaceUtil.logException(message, e);
            throw new CertificateStoreException(message, e);
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Method to update the certificate which matches the given alias.
 *
 * @param certificate: The base64 encoded certificate string.
 * @param alias        : Alias of the certificate that should be retrieved.
 * @return :/*  w  ww .  j a  v a 2s . com*/
 */
public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {

    InputStream certificateStream = null;
    try {
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.getCertificate(alias) == null) {
            log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found"
                    + " in the trust store.");
            return ResponseCode.CERTIFICATE_NOT_FOUND;
        }

        //Generate the certificate from the input string.
        byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8)));
        certificateStream = new ByteArrayInputStream(cert);

        if (certificateStream.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        Certificate newCertificate = certificateFactory.generateCertificate(certificateStream);
        X509Certificate x509Certificate = (X509Certificate) newCertificate;

        if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
            log.error("Could not update the certificate. The certificate expired.");
            return ResponseCode.CERTIFICATE_EXPIRED;
        }
        // If the certificate is not expired, delete the existing certificate and add the new cert.
        trustStore.deleteEntry(alias);
        //Store the certificate in the trust store.
        trustStore.setCertificateEntry(alias, newCertificate);
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
    } catch (IOException e) {
        throw new CertificateManagementException("Error updating certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error generating the certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Error loading the keystore.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
    } finally {
        closeStreams(fileOutputStream, certificateStream, localTrustStoreStream);
    }
    return ResponseCode.SUCCESS;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the certificate information from base64 encoded certificate.
 *
 * @param base64EncodedCertificate Base 64 encoded certificate.
 * @return Certificate information.//from www.  j  a  v  a2 s .c  o m
 */
public CertificateInformationDTO getCertificateInfo(String base64EncodedCertificate) {
    CertificateInformationDTO certificateInformationDTO = null;
    try {
        byte[] cert = (Base64.decodeBase64(base64EncodedCertificate.getBytes(StandardCharsets.UTF_8)));
        InputStream serverCert = new ByteArrayInputStream(cert);
        if (serverCert.available() == 0) {
            log.error(
                    "Provided certificate is empty for getting certificate information. Hence please provide a "
                            + "non-empty certificate to overcome this issue.");
        }
        CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        while (serverCert.available() > 0) {
            Certificate certificate = cf.generateCertificate(serverCert);
            certificateInformationDTO = getCertificateMetaData((X509Certificate) certificate);
        }
    } catch (IOException | CertificateException e) {
        log.error("Error while getting the certificate information from the certificate", e);
    }
    return certificateInformationDTO;
}

From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * To get the unique identifier(serialnumber_issuerdn) of the certificate.
 *
 * @param certificate Base64 encoded certificate.
 * @return unique identifier of the certification.
 *//*from   w w w  . ja  v a2  s.c  o  m*/
public String getUniqueIdentifierOfCertificate(String certificate) {
    byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8)));
    ByteArrayInputStream serverCert = new ByteArrayInputStream(cert);
    String uniqueIdentifier = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        while (serverCert.available() > 0) {
            Certificate generatedCertificate = cf.generateCertificate(serverCert);
            X509Certificate x509Certificate = (X509Certificate) generatedCertificate;
            uniqueIdentifier = String
                    .valueOf(x509Certificate.getSerialNumber() + "_" + x509Certificate.getIssuerDN());
            uniqueIdentifier = uniqueIdentifier.replaceAll(",", "#").replaceAll("\"", "'");
        }
    } catch (CertificateException e) {
        log.error("Error while getting serial number of the certificate.", e);
    } finally {
        closeStreams(serverCert);
    }
    return uniqueIdentifier;
}

From source file:eu.europa.ec.markt.dss.validation.pades.PDFDocumentValidator.java

private boolean checkVriDict(PdfDictionary vriSigDictionary, boolean _vriVerificationresult,
        PAdESSignature pades, ValidationContext ctx, String hexHash)
        throws CertificateException, IOException, CRLException, OCSPException {

    boolean vriVerificationresult = _vriVerificationresult;

    if (vriSigDictionary == null) {
        LOG.info("Couldn't find the signature VRI identified by " + hexHash + " in the DSS");
        vriVerificationresult = false;//w w w  . ja  va2 s .c om
    } else {
        LOG.info("Found the signature VRI identified by " + hexHash + " in the DSS");

        // Verify the certs in the VRI
        PdfArray vricert = vriSigDictionary.getAsArray(new PdfName("Cert"));
        if (vricert != null) {
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            List<X509Certificate> certs = new ArrayList<X509Certificate>();
            for (int i = 0; i < vricert.size(); i++) {
                PdfStream stream = vricert.getAsStream(i);
                certs.add((X509Certificate) factory.generateCertificate(
                        new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream))));
            }
            vriVerificationresult &= everyCertificateValueAreThere(ctx, certs, pades.getSigningCertificate());
        }

        // Verify the CRLs in the VRI
        PdfArray vricrl = vriSigDictionary.getAsArray(new PdfName("CRL"));
        if (vricrl != null) {
            CertificateFactory factory = CertificateFactory.getInstance("X509");
            List<X509CRL> crls = new ArrayList<X509CRL>();
            for (int i = 0; i < vricrl.size(); i++) {
                PdfStream stream = vricrl.getAsStream(i);
                crls.add((X509CRL) factory
                        .generateCRL(new ByteArrayInputStream(PdfReader.getStreamBytes((PRStream) stream))));
            }
            vriVerificationresult &= everyCRLValueOrRefAreThere(ctx, crls);
        }

        // Verify the OCSPs in the VRI
        PdfArray vriocsp = vriSigDictionary.getAsArray(new PdfName("OCSP"));
        if (vriocsp != null) {
            List<BasicOCSPResp> ocsps = new ArrayList<BasicOCSPResp>();
            for (int i = 0; i < vriocsp.size(); i++) {
                PdfStream stream = vriocsp.getAsStream(i);
                ocsps.add((BasicOCSPResp) new OCSPResp(PdfReader.getStreamBytes((PRStream) stream))
                        .getResponseObject());
            }
            vriVerificationresult &= everyOCSPValueOrRefAreThere(ctx, ocsps);
        }

    }

    return vriVerificationresult;
}