Example usage for org.bouncycastle.asn1.x509 Certificate getInstance

List of usage examples for org.bouncycastle.asn1.x509 Certificate getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Certificate getInstance.

Prototype

public static Certificate getInstance(Object obj) 

Source Link

Usage

From source file:eu.europa.ec.markt.dss.validation102853.CAdESCertificateSource.java

License:Open Source License

/**
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 *
 *//*w w w. j a v  a  2s .co m*/
private ArrayList<CertificateToken> extractEncapsulatedCertificates() throws DSSException {

    final ArrayList<CertificateToken> encapsulatedCerts = new ArrayList<CertificateToken>();
    try {

        // Gets certificates from CAdES-XL certificate-values inside SignerInfo attribute if present
        if (signerInformation != null && signerInformation.getUnsignedAttributes() != null) {

            final Attribute attr = signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_certValues);
            if (attr != null) {

                final ASN1Sequence seq = (ASN1Sequence) attr.getAttrValues().getObjectAt(0);
                for (int ii = 0; ii < seq.size(); ii++) {

                    final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
                    final X509Certificate cert = new X509CertificateObject(cs);
                    final CertificateToken certToken = addCertificate(cert);
                    if (!encapsulatedCerts.contains(certToken)) {

                        encapsulatedCerts.add(certToken);
                    }
                }
            }
        }

        //TODO (cades): Read UnsignedAttribute: S/MIME Authenticated Attributes {iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) aa(2) id-aa-ets-CertificateRefs(21)}

        //TODO (cades): Read certificates from inner timestamps (signature timestamps and archive timestamps) ?

    } catch (CertificateParsingException e) {

        throw new DSSException(e);
    }
    return encapsulatedCerts;
}

From source file:eu.europa.ec.markt.dss.validation102853.TimestampToken.java

License:Open Source License

/**
 * Constructor with an indication of the time-stamp type. The default constructor for TimestampToken.
 *///from www.  j a v a2 s .c o m
public TimestampToken(final TimeStampToken timeStamp, final TimestampType type,
        final CertificatePool certPool) {

    this.timeStamp = timeStamp;
    this.timeStampType = type;
    this.extraInfo = new TokenValidationExtraInfo();
    wrappedSource = new CAdESCertificateSource(timeStamp, certPool);
    final Collection<CertificateToken> certs = wrappedSource.getCertificates();
    for (final CertificateToken certificateToken : certs) {

        final byte[] encoded = certificateToken.getEncoded();
        final Certificate certificate = Certificate.getInstance(encoded);
        final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(certificate);
        //TODO(2013-11-29 Nicolas BC149): check that the matching is correct
        // if (timeStamp.getSID().match(cert.getCertificate())) {
        if (timeStamp.getSID().match(x509CertificateHolder)) {

            boolean valid = isSignedBy(certificateToken);
            if (valid) {
                break;
            }
        }
    }
}

From source file:eu.europa.esig.dss.validation.CAdESCertificateSource.java

License:Open Source License

private void extractCertificateFromUnsignedAttribute(List<CertificateToken> encapsulatedCerts,
        ASN1ObjectIdentifier oid) {/*from ww w.  jav  a  2s.c o  m*/
    final Attribute attribute = signerInformation.getUnsignedAttributes().get(oid);
    if (attribute != null) {
        final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0);
        for (int ii = 0; ii < seq.size(); ii++) {
            try {
                final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
                final X509Certificate cert = new X509CertificateObject(cs);
                final CertificateToken certToken = addCertificate(new CertificateToken(cert));
                if (!encapsulatedCerts.contains(certToken)) {
                    encapsulatedCerts.add(certToken);
                }
            } catch (Exception e) {
                logger.warn("Unable to parse encapsulated certificate : " + e.getMessage());
            }
        }
    }
}

From source file:eu.europa.esig.dss.validation.TimestampToken.java

License:Open Source License

/**
 * Constructor with an indication of the timestamp type. The default constructor for {@code TimestampToken}.
 *
 * @param timeStamp/*from   w w w. jav  a  2s  . c om*/
 *            {@code TimeStampToken}
 * @param type
 *            {@code TimestampType}
 * @param certPool
 *            {@code CertificatePool} which is used to identify the signing certificate of the timestamp
 */
public TimestampToken(final TimeStampToken timeStamp, final TimestampType type,
        final CertificatePool certPool) {

    this.timeStamp = timeStamp;
    this.timeStampType = type;
    this.extraInfo = new TokenValidationExtraInfo();
    wrappedSource = new CAdESCertificateSource(timeStamp, certPool);
    final Collection<CertificateToken> certs = wrappedSource.getCertificates();
    for (final CertificateToken certificateToken : certs) {

        final byte[] encoded = certificateToken.getEncoded();
        final Certificate certificate = Certificate.getInstance(encoded);
        final X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(certificate);
        if (timeStamp.getSID().match(x509CertificateHolder)) {

            boolean valid = isSignedBy(certificateToken);
            if (valid) {
                break;
            }
        }
    }
}

From source file:it.scoppelletti.spaceship.security.FakeCertificateFactory.java

License:Apache License

@SuppressWarnings({ "deprecation", "TryFinallyCanBeTryWithResources" })
public static X509Certificate create(PublicKey publicKey, FakeKeyPairGeneratorSpec spec)
        throws IOException, CertificateParsingException {
    ASN1ObjectIdentifier sigAlgOid;//ww w. jav a 2 s .  c  o  m
    AlgorithmIdentifier sigAlgId;
    org.bouncycastle.jce.X509Principal subject;
    ASN1EncodableVector result;
    Certificate cert;
    org.bouncycastle.jce.provider.X509CertificateObject x509Cert;
    TBSCertificate tbsCertificate;
    ASN1InputStream publicKeyInfoIn = null;
    V3TBSCertificateGenerator tbsGenerator;
    byte[] signature;

    sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
    sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
    signature = new byte[1];

    tbsGenerator = new V3TBSCertificateGenerator();
    try {
        publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded());
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    } finally {
        if (publicKeyInfoIn != null) {
            publicKeyInfoIn.close();
        }
    }

    subject = new org.bouncycastle.jce.X509Principal(spec.getSubject().getEncoded());

    tbsGenerator.setSerialNumber(new ASN1Integer(spec.getSerialNumber()));
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(spec.getStartDate()));
    tbsGenerator.setEndDate(new Time(spec.getEndDate()));
    tbsGenerator.setSignature(sigAlgId);

    tbsCertificate = tbsGenerator.generateTBSCertificate();

    result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));

    cert = Certificate.getInstance(new DERSequence(result));
    x509Cert = new org.bouncycastle.jce.provider.X509CertificateObject(cert);
    return x509Cert;
}

From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java

License:Open Source License

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert//ww w . ja  v  a 2  s  . c o  m
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey,
        SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions,
        Provider provider) throws CryptoException {

    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(
                cert.getSubjectX500Principal(), cert.getPublicKey());

        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }

        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }

        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }

        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }

        ContentSigner contentSigner = null;

        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider)
                    .build(privateKey);
        }

        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);

        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }

        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}

From source file:net.wstech2.me.httpsclient.CertificateStore.java

License:Apache License

/**
 * Gets a certificate from the Certificate Store corresponding to the
 * subject passed as parameter./* ww  w.  j  a va2  s . co m*/
 * 
 * @param cn
 *            common name
 * 
 * @return The certificate corresponding to the common name informed. Null
 *         if no certificate could be found.
 * @throws RecordStoreException
 * @throws InvalidRecordIDException
 * @throws RecordStoreNotOpenException
 */
public Certificate get(String cn)
        throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException {
    if (certificateIdsMap.get(cn) == null) {
        return null;
    }
    int recordId = Integer.valueOf((String) certificateIdsMap.get(cn)).intValue();
    return Certificate.getInstance(recordStore.getRecord(recordId));
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * Loads a certificate either from the device record store or from the
 * application jar.//from  ww  w .  ja  va2 s.c om
 * 
 * @param fullCN
 *            The common name attribute identifying the certificate, like
 *            "CN = j2metest.local,O = j2me-teste-org,L = Curitiba,ST = PR,C = BR"
 *            .
 * @param friendlyCN
 *            the friendly common name, like j2metest.local.
 * @return An instance of org.bouncycastle.asn1.x509.Certificate
 *         corresponding to the certificate loaded or null if a certificate
 *         was not found.
 * @throws RecordStoreNotOpenException
 * @throws InvalidRecordIDException
 * @throws RecordStoreException
 * @throws IOException
 */
public static org.bouncycastle.asn1.x509.Certificate getCertificateFromJarOrRecordStore(String fullCN,
        String friendlyCN)
        throws RecordStoreNotOpenException, InvalidRecordIDException, RecordStoreException, IOException {
    Certificate cert = null;
    byte[] certBA = loadJarResource("/res/certs/" + fullCN + ".der");
    if (certBA == null) {
        if (friendlyCN == null) {
            friendlyCN = getFriendlyCNFromFullSubjectName(fullCN);
        }
        certBA = loadJarResource("/res/certs/" + friendlyCN + ".der");
    }
    if (certBA != null && certBA.length != 0) {
        cert = Certificate.getInstance(certBA);
    }
    return cert;
}

From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java

License:Open Source License

/**
 * Converts a {@link java.security.cert.X509Certificate} to a {@link Certificate}.
 *
 * @param cert - the X509Certificate to convert.
 * @return a {@link Certificate}.//from   w  ww . j  a  v  a2  s  .  c  o  m
 * @throws OcspCheckerException after posting an alert to the admin console, if any error occurs.
 */
@VisibleForTesting
Certificate convertToBouncyCastleCert(X509Certificate cert) throws OcspCheckerException {
    try {
        byte[] data = cert.getEncoded();
        return Certificate.getInstance(data);
    } catch (CertificateEncodingException e) {
        throw new OcspCheckerException(
                "Unable to convert X509 certificate to a Bouncy Castle certificate." + NOT_VERIFIED_MSG, e);
    }
}

From source file:org.codice.ddf.security.ocsp.checker.OcspCheckerTest.java

License:Open Source License

private static Certificate getBouncyCastleCertificate(X509Certificate cert) throws Exception {
    return Certificate.getInstance(cert.getEncoded());
}