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.codice.ddf.security.idp.client.SimpleSign.java

public boolean validateSignature(String queryParamsToValidate, String encodedSignature, String encodedPublicKey)
        throws SignatureException {
    try {//ww w  .j  av a 2 s.com
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(encodedPublicKey)));

        String jceSigAlgo = "SHA1withRSA";
        if ("DSA".equalsIgnoreCase(certificate.getPublicKey().getAlgorithm())) {
            jceSigAlgo = "SHA1withDSA";
        }

        java.security.Signature sig = java.security.Signature.getInstance(jceSigAlgo);
        sig.initVerify(certificate.getPublicKey());
        sig.update(queryParamsToValidate.getBytes("UTF-8"));
        return sig.verify(Base64.decodeBase64(encodedSignature));
    } catch (NoSuchAlgorithmException | InvalidKeyException | CertificateException
            | UnsupportedEncodingException | java.security.SignatureException e) {
        throw new SignatureException(e);
    }
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.//from   ww w.j  a  va 2s  . c o m
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.ejbca.extra.ra.ExtRATestClient.java

ExtRATestClient(String[] args) throws Exception {
    CryptoProviderTools.installBCProvider();
    if (args.length != 8) {
        log.debug("Number of arguments: " + args.length);
        help();//w w  w .j a  v  a  2  s . c om
        System.exit(-1); // NOPMD, it's not a JEE app
    } else {
        requestKeyStore = args[ARG_TYPE].equalsIgnoreCase(TYPE_KEYSTORE);
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("external-ra-cli");
        msghome = new MessageHome(entityManagerFactory, MessageHome.MESSAGETYPE_EXTRA, true);
        securitylevel = args[ARG_SECURITYLEVEL];
        if (!securitylevel.equalsIgnoreCase(SECURITY_UNSECURED)
                && !securitylevel.equalsIgnoreCase(SECURITY_SIGNED)
                && !securitylevel.equalsIgnoreCase(SECURITY_ENCRYPTED)
                && !securitylevel.equalsIgnoreCase(SECURITY_SIGNEDENCRYPTED)) {
            throw new Exception("Invalid SecurityLevel: " + securitylevel);
        }
        if (securitylevel.equalsIgnoreCase(SECURITY_SIGNED)
                || securitylevel.equalsIgnoreCase(SECURITY_SIGNEDENCRYPTED)) {
            RAKeyStore rakeystore = new RAKeyStore(args[ARG_KEYSTOREPATH], args[ARG_PASSWORD]);
            Certificate[] chain = rakeystore.getKeyStore().getCertificateChain(rakeystore.getAlias());
            cAChain = new Vector();
            for (int i = 0; i < chain.length; i++) {
                if (((X509Certificate) chain[i]).getBasicConstraints() != -1) {
                    cAChain.add(chain[i]);
                }
            }
            raKey = (PrivateKey) rakeystore.getKeyStore().getKey(rakeystore.getAlias(),
                    args[ARG_PASSWORD].toCharArray());
            raCert = (X509Certificate) rakeystore.getKeyStore().getCertificate(rakeystore.getAlias());
        }
        if (securitylevel.equalsIgnoreCase(SECURITY_ENCRYPTED)
                || securitylevel.equalsIgnoreCase(SECURITY_SIGNEDENCRYPTED)) {
            CertificateFactory cf = CertTools.getCertificateFactory();
            encCert = (X509Certificate) cf.generateCertificate(new FileInputStream(args[ARG_ENCRYPTIONCERT]));
        }
        reqPerMin = Integer.parseInt(args[ARG_REQUESTSPERMIN]);
        concurrentRAs = Integer.parseInt(args[ARG_CONCURRENTRAS]);
        waitTime = Integer.parseInt(args[ARG_WAITTIME]);
    }
}

From source file:org.apache.tomcat.util.net.jsse.JSSESupport.java

protected java.security.cert.X509Certificate[] getX509Certificates(SSLSession session) throws IOException {
    X509Certificate jsseCerts[] = null;
    try {//from w w w  .  ja  v  a 2 s.  c  om
        jsseCerts = session.getPeerCertificateChain();
    } catch (Throwable ex) {
        // Get rid of the warning in the logs when no Client-Cert is
        // available
    }

    if (jsseCerts == null)
        jsseCerts = new X509Certificate[0];
    java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[jsseCerts.length];
    for (int i = 0; i < x509Certs.length; i++) {
        try {
            byte buffer[] = jsseCerts[i].getEncoded();
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
            x509Certs[i] = (java.security.cert.X509Certificate) cf.generateCertificate(stream);
            if (log.isTraceEnabled())
                log.trace("Cert #" + i + " = " + x509Certs[i]);
        } catch (Exception ex) {
            log.info("Error translating " + jsseCerts[i], ex);
            return null;
        }
    }

    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}

From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java

private X509Certificate getCertificate(String certificate) {
    if (certificate.isEmpty()) {
        return null;
    }//from  w w w .j  av a 2  s  . com

    if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
        final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE)
                + KeyStoreConstant.BEGIN_CERTIFICATE.length();
        final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
        certificate = certificate.substring(fIdx, sIdx);
    }
    final byte[] byteCert = Base64.decodeBase64(certificate);
    final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
    CertificateFactory certFactory;
    try {
        certFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
        newCert.checkValidity();
        return newCert;
    } catch (final CertificateException e) {
        LOG.error("Failed to get certificate", e);
        return null;
    }
}

From source file:eu.optimis.trustedinstance.TrustedInstanceImpl.java

private synchronized void initialize() {
    //storage = new DBStorage();

    String keystore = ComponentConfigurationProvider.getString("trusted.instance.keystore"); //$NON-NLS-1$
    String password = ComponentConfigurationProvider.getString("trusted.instance.keystore.password"); //$NON-NLS-1$
    String alias = ComponentConfigurationProvider.getString("trusted.instance.keystore.alias"); //$NON-NLS-1$
    String publicCert = ComponentConfigurationProvider.getString("trusted.instance.keystore.public.cert"); //$NON-NLS-1$
    infoServiceName = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.name");
    infoServiceUrl = ComponentConfigurationProvider.getString("trusted.instance.infoservice.client.url");

    try {/*  w  ww.  j  a  va  2  s .c om*/

        keyStore_input_stream = getClass().getResourceAsStream(keystore);

        if (keyStore_input_stream == null) {
            throw new Exception("unable to load keystore of the trusted instance");
        }

        if (password == null) {
            throw new Exception("unable to load passowrd of the keystore");
        }

        ti_keyStorePass = password.toCharArray();

        if (alias == null) {
            throw new Exception("unable to load alias of the keystore");
        }

        ti_keyStoreAlias = alias;

        publicCert_input_stream = getClass().getResourceAsStream(publicCert);

        if (publicCert_input_stream == null) {
            throw new Exception("unable to load public certificate of the trusted instance");
        }

        CertificateFactory ti_cf = CertificateFactory.getInstance("X.509");
        ti_certificate = (X509Certificate) ti_cf.generateCertificate(publicCert_input_stream);

        ti_ks = KeyStore.getInstance("JKS");
        ti_ks.load(keyStore_input_stream, ti_keyStorePass);

        if (infoServiceName == null) {
            throw new Exception("unable to find name for ProviderInfoService");
        }

        if (infoServiceUrl == null) {
            throw new Exception("unable to find URL for ProviderInfoService");
        }

    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
    }
}

From source file:org.sinekartads.dto.domain.CertificateDTO.java

public X509Certificate rawX509CertificateFromHex() {

    if (hexCertificate != null)
        return null;

    try {/*from w w w .  j a va  2s.  c o m*/
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate rawX509Certificate = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(HexUtils.decodeHex(hexCertificate)));
        return rawX509Certificate;
    } catch (CertificateException e) {
        // never thrown, using the TsTokenDTO protocol the certificate hex has to be correct
        throw new RuntimeException(e);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testReadFiles() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();
    beIDCard.addCardListener(new TestBeIDCardListener());

    LOG.debug("reading identity file");
    final byte[] identityFile = beIDCard.readFile(FileType.Identity);
    LOG.debug("reading identity signature file");
    final byte[] identitySignatureFile = beIDCard.readFile(FileType.IdentitySignature);
    LOG.debug("reading RRN certificate file");
    final byte[] rrnCertificateFile = beIDCard.readFile(FileType.RRNCertificate);
    LOG.debug("reading Photo file");
    final byte[] photoFile = beIDCard.readFile(FileType.Photo);

    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate rrnCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(rrnCertificateFile));

    beIDCard.close();//ww  w .ja va  2s .com

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final Identity identity = beIDIntegrity.getVerifiedIdentity(identityFile, identitySignatureFile, photoFile,
            rrnCertificate);

    assertNotNull(identity);
    assertNotNull(identity.getNationalNumber());
}

From source file:test.integ.be.fedict.commons.eid.client.BeIDCardTest.java

@Test
public void testAddressFileValidation() throws Exception {
    final BeIDCard beIDCard = getBeIDCard();
    beIDCard.addCardListener(new TestBeIDCardListener());

    LOG.debug("reading address file");
    final byte[] addressFile = beIDCard.readFile(FileType.Address);
    LOG.debug("reading address signature file");
    final byte[] addressSignatureFile = beIDCard.readFile(FileType.AddressSignature);
    LOG.debug("reading identity signature file");
    final byte[] identitySignatureFile = beIDCard.readFile(FileType.IdentitySignature);
    LOG.debug("reading RRN certificate file");
    final byte[] rrnCertificateFile = beIDCard.readFile(FileType.RRNCertificate);

    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate rrnCertificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(rrnCertificateFile));

    beIDCard.close();//from  w w w . j  ava  2  s .  co m

    final BeIDIntegrity beIDIntegrity = new BeIDIntegrity();
    final Address address = beIDIntegrity.getVerifiedAddress(addressFile, identitySignatureFile,
            addressSignatureFile, rrnCertificate);

    assertNotNull(address);
    assertNotNull(address.getMunicipality());
}

From source file:com.microsoft.azure.batch.CertificateOperations.java

/**
 * Creates a new {@link Certificate} from .cer format data in stream.
 *
 * @param certStream The certificate data in .cer format.
 * @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request.
 * @throws BatchErrorException Exception thrown from REST call
 * @throws IOException Exception thrown from serialization/deserialization
 * @throws CertificateException Exception thrown on parsing errors
 * @throws NoSuchAlgorithmException Exception thrown if the X509 provider is not registered in the security provider list.
 *///from w  ww .ja  v  a  2  s. c o m
public void createCertificate(InputStream certStream, Iterable<BatchClientBehavior> additionalBehaviors)
        throws BatchErrorException, IOException, CertificateException, NoSuchAlgorithmException {
    CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) x509CertFact.generateCertificate(certStream);

    CertificateAddParameter addParam = new CertificateAddParameter();
    addParam.withCertificateFormat(CertificateFormat.CER);
    addParam.withThumbprintAlgorithm(SHA1_CERTIFICATE_ALGORITHM);
    addParam.withThumbprint(getThumbPrint(cert));
    addParam.withData(Base64.encodeBase64String(cert.getEncoded()));

    createCertificate(addParam, additionalBehaviors);
}