Example usage for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

List of usage examples for org.bouncycastle.asn1.x509 GeneralNames GeneralNames

Introduction

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

Prototype

private GeneralNames(ASN1Sequence seq) 

Source Link

Usage

From source file:es.gob.afirma.signers.cades.CAdESUtils.java

License:Open Source License

/** Genera una estructura <i>SigningCertificateV2</i> seg&uacute;n RFC 5035:
 *
 * <pre>/*w  w w  .  j a v a 2  s .co  m*/
 * id-aa-signingCertificateV2 OBJECT IDENTIFIER ::= { iso(1)
 *      member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
 *      smime(16) id-aa(2) 47
 * }
 *
 * SigningCertificateV2 ::=  SEQUENCE {
 *      certs        SEQUENCE OF ESSCertIDv2,
 *      policies     SEQUENCE OF PolicyInformation OPTIONAL
 * }
 * </pre>
 *
 * @param cert Certificado del firmante
 * @param digestAlgorithmName Nombre del algoritmo de huella digital a usar
 * @param policy Pol&iacute;tica de firma
 * @return Estructura <i>SigningCertificateV2</i> seg&uacute;n RFC 5035
 * @throws CertificateEncodingException Si el certificado proporcionado no es v&aacute;lido
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella indicado
 * @throws IOException Si hay errores en el tratamiento de datos */
private static Attribute getSigningCertificateV2(final X509Certificate cert, final String digestAlgorithmName,
        final AdESPolicy policy) throws CertificateEncodingException, NoSuchAlgorithmException, IOException {

    // ALGORITMO DE HUELLA DIGITAL
    final AlgorithmIdentifier digestAlgorithmOID = SigUtils
            .makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName));

    // INICIO SINGING CERTIFICATE-V2

    /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
     * CertificateSerialNumber */

    final GeneralNames gns = new GeneralNames(
            new GeneralName(X500Name.getInstance(cert.getIssuerX500Principal().getEncoded())));

    final IssuerSerial isuerSerial = new IssuerSerial(gns, cert.getSerialNumber());

    /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
     * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
     * IssuerSerial OPTIONAL }
     * Hash ::= OCTET STRING */

    final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded());
    final ESSCertIDv2[] essCertIDv2 = { new ESSCertIDv2(digestAlgorithmOID, certHash, isuerSerial) };

    /** PolicyInformation ::= SEQUENCE {
     *    policyIdentifier CertPolicyId,
     *    policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo OPTIONAL
     *  }
     *  CertPolicyId ::= OBJECT IDENTIFIER
     *  PolicyQualifierInfo ::= SEQUENCE {
     *    policyQualifierId PolicyQualifierId,
     *    qualifier ANY DEFINED BY policyQualifierId
     *  } */

    final SigningCertificateV2 scv2;
    if (policy != null && policy.getPolicyIdentifier() != null) {

        /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
         * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
         * } */
        scv2 = new SigningCertificateV2(essCertIDv2, getPolicyInformation(policy)); // con politica
    } else {
        scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
    }

    return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2));

}

From source file:es.gob.afirma.signers.cades.CAdESUtils.java

License:Open Source License

/** Genera una estructura <i>SigningCertificateV2</i> seg&uacute;n RFC 5035:
 *
 * <pre>//ww  w .  j  a v a2 s  .  c o m
 * id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
 *      member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
 *      smime(16) id-aa(2) 12
 * }
 *
 * SigningCertificate ::=  SEQUENCE {
 *      certs        SEQUENCE OF ESSCertID,
 *      policies     SEQUENCE OF PolicyInformation OPTIONAL
 * }
 * </pre>
 *
 * @param cert Certificado del firmante
 * @param digestAlgorithmName Nombre del algoritmo de huella digital a usar
 * @param policy Pol&iacute;tica de firma
 * @return Estructura <i>SigningCertificate</i> seg&uacute;n RFC 5035
 * @throws CertificateEncodingException Si el certificado proporcionado no es v&aacute;lido
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella indicado */
private static Attribute getSigningCertificateV1(final X509Certificate cert, final String digestAlgorithmName,
        final AdESPolicy policy) throws CertificateEncodingException, NoSuchAlgorithmException {

    // INICIO SINGNING CERTIFICATE

    /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
     * CertificateSerialNumber } */

    final GeneralName gn = new GeneralName(X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()));
    final GeneralNames gns = new GeneralNames(gn);

    final IssuerSerial isuerSerial = new IssuerSerial(gns, cert.getSerialNumber());

    /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
     * OPTIONAL }
     * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
    final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded());
    final ESSCertID essCertID = new ESSCertID(certHash, isuerSerial);

    /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
     * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
     * OPTIONAL }
     * CertPolicyId ::= OBJECT IDENTIFIER
     * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
     * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

    final SigningCertificate scv;
    if (policy != null && policy.getPolicyIdentifier() != null) {

        /** SigningCertificateV2 ::= SEQUENCE {
         *    certs SEQUENCE OF ESSCertIDv2,
         *    policies SEQUENCE OF PolicyInformation OPTIONAL
         *  } */

        /*
         * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
         * CASTLE NO TIENE DICHO CONSTRUCTOR.
         */
        final ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERSequence(essCertID));
        v.add(new DERSequence(getPolicyInformation(policy)));
        scv = SigningCertificate.getInstance(new DERSequence(v)); // con politica
    } else {
        scv = new SigningCertificate(essCertID); // Sin politica
    }

    /** id-aa-signingCertificate OBJECT IDENTIFIER ::= {
     *    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) id-aa(2) 12
     *  } */

    return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(scv));
}

From source file:esteidhacker.FakeEstEIDCA.java

License:Open Source License

public X509Certificate generateUserCertificate(RSAPublicKey pubkey, boolean signature, String firstname,
        String lastname, String idcode, String email)
        throws InvalidKeyException, ParseException, IOException, IllegalStateException, NoSuchProviderException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {
    Date startDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2015-01-01");
    Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2015-12-31");

    String template = "C=EE,O=ESTEID,OU=%s,CN=%s\\,%s\\,%s,SURNAME=%s,GIVENNAME=%s,SERIALNUMBER=%s";
    // Normalize.
    lastname = lastname.toUpperCase();/*from w  ww .j  av a2 s .  c  o m*/
    firstname = firstname.toUpperCase();
    idcode = idcode.toUpperCase();
    email = email.toLowerCase();
    String subject = String.format(template, (signature ? "digital signature" : "authentication"), lastname,
            firstname, idcode, lastname, firstname, idcode);

    byte[] serialBytes = new byte[16];
    SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG");
    rnd.nextBytes(serialBytes);
    serialBytes[0] &= 0x7F; // Can't be negative
    BigInteger serial = new BigInteger(serialBytes);

    X509CertificateHolder real;
    if (signature) {
        real = getRealCert("/resources/sk-sign.pem");
    } else {
        real = getRealCert("/resources/sk-auth.pem");
    }
    serial = real.getSerialNumber();
    System.out.println("Generating from subject: " + real.getSubject());
    System.out.println("Generating subject: " + new X500Name(subject).toString());

    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(real.getIssuer(), serial, startDate,
            endDate, new X500Name(subject), pubkey);

    @SuppressWarnings("unchecked")
    List<ASN1ObjectIdentifier> list = real.getExtensionOIDs();

    // Copy all extensions, except altName
    for (ASN1ObjectIdentifier extoid : list) {
        Extension ext = real.getExtension(extoid);
        if (ext.getExtnId().equals(Extension.subjectAlternativeName)) {
            // altName must be changed
            builder.addExtension(ext.getExtnId(), ext.isCritical(),
                    new GeneralNames(new GeneralName(GeneralName.rfc822Name, email)));
        } else {
            builder.copyAndAddExtension(ext.getExtnId(), ext.isCritical(), real);
        }
    }

    // Generate cert
    ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(esteidKey);

    X509CertificateHolder cert = builder.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
            .getCertificate(cert);
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.GWCertificateUtilsBc.java

License:Apache License

/**
 * //  ww w .j  a va2 s  . c  om
 * @param entityKey - public key of the requesting GW
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509CertificateHolder buildEndEntityCert(X500Name subject, AsymmetricKeyParameter entityKey,
        AsymmetricKeyParameter caKey, X509CertificateHolder caCert, String ufn) throws Exception {
    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey);

    if (subject == null)
        subject = new X500Name("CN = BETaaS Gateway Certificate");

    X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            subject, entityKeyInfo);

    X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator());

    certBldr.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extUtils.createSubjectKeyIdentifier(entityKeyInfo))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment))
            .addExtension(Extension.subjectAlternativeName, false,
                    new GeneralNames(new GeneralName(GeneralName.rfc822Name, ufn)));

    AlgorithmIdentifier sigAlg = algFinder.find(ALG_NAME);
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(caKey);

    return certBldr.build(signer);
}

From source file:eu.betaas.taas.securitymanager.common.certificate.utils.GWCertificateUtilsBc.java

License:Apache License

/**
* A method to build PKCS10 Certification request (BC style)
* @param subject: the subject info/data in X500Name format
* @param kp: the subject's key pair//from www.  j a  v  a 2 s.c  o  m
* @param subjectAltName: subject's UFN
* @return
* @throws Exception
*/
public static PKCS10CertificationRequest buildCertificateRequest(X500Name subject, AsymmetricCipherKeyPair kp,
        String subjectAltName) throws Exception {
    String sigName = "SHA1withECDSA";
    SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder();

    PKCS10CertificationRequestBuilder requestBuilder = new BcPKCS10CertificationRequestBuilder(subject,
            kp.getPublic());

    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, subjectAltName + "@betaas.eu")));
    requestBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());

    AlgorithmIdentifier sigAlg = algFinder.find(sigName);
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(kp.getPrivate());

    PKCS10CertificationRequest req1 = requestBuilder.build(signer);

    return req1;
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.RFC3280CertPathUtilitiesHelper.java

License:Open Source License

/**
 * Checks a certificate if it is revoked.
 * /* w  w  w.ja v a  2s  . co m*/
 * @param paramsPKIX PKIX parameters.
 * @param cert Certificate to check if it is revoked.
 * @param validDate The date when the certificate revocation status
 *                should be checked.
 * @param sign The issuer certificate of the certificate
 *                <code>cert</code>.
 * @param workingPublicKey The public key of the issuer certificate
 *                <code>sign</code>.
 * @param certPathCerts The certificates of the certification path.
 * @throws AnnotatedException if the certificate is revoked or the
 *                 status cannot be checked or some error occurs.
 */
protected static void checkCRLs2(ExtPKIXParameters paramsPKIX, X509Certificate cert, Date validDate,
        X509Certificate sign, PublicKey workingPublicKey, List<?> certPathCerts)
        throws SimpleValidationErrorException {
    SimpleValidationErrorException lastException = null;
    CRLDistPoint crldp = null;
    try {
        crldp = CRLDistPoint.getInstance(CertPathValidatorUtilities.getExtensionValue(cert,
                RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS));
    } catch (Exception e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
    }
    try {
        CertPathValidatorUtilities.addAdditionalStoresFromCRLDistributionPoint(crldp, paramsPKIX);
    } catch (AnnotatedException e) {
        throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
    }
    CertStatus certStatus = new CertStatus();
    ReasonsMask reasonsMask = new ReasonsMask();

    boolean validCrlFound = false;
    // for each distribution point
    if (crldp != null) {
        DistributionPoint dps[] = null;
        try {
            dps = crldp.getDistributionPoints();
        } catch (Exception e) {
            throw new SimpleValidationErrorException(ValidationErrorCode.crlDistPtExtError, e);
        }
        if (dps != null) {
            for (int i = 0; i < dps.length && certStatus.getCertStatus() == CertStatus.UNREVOKED
                    && !reasonsMask.isAllReasons(); i++) {
                ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone();
                try {
                    checkCRL(dps[i], paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus,
                            reasonsMask, certPathCerts);
                    validCrlFound = true;
                } catch (SimpleValidationErrorException e) {
                    lastException = e;
                }
            }
        }
    }

    /*
     * If the revocation status has not been determined, repeat the
     * process above with any available CRLs not specified in a
     * distribution point but issued by the certificate issuer.
     */

    if (certStatus.getCertStatus() == CertStatus.UNREVOKED && !reasonsMask.isAllReasons()) {
        try {
            /*
             * assume a DP with both the reasons and the
             * cRLIssuer fields omitted and a distribution
             * point name of the certificate issuer.
             */
            ASN1Primitive issuer = null;
            try {
                issuer = new ASN1InputStream(
                        CertPathValidatorUtilities.getEncodedIssuerPrincipal(cert).getEncoded()).readObject();
            } catch (Exception e) {
                throw new SimpleValidationErrorException(ValidationErrorCode.crlIssuerException, e);
            }
            DistributionPoint dp = new DistributionPoint(new DistributionPointName(0,
                    new GeneralNames(new GeneralName(GeneralName.directoryName, issuer))), null, null);
            ExtendedPKIXParameters paramsPKIXClone = (ExtendedPKIXParameters) paramsPKIX.clone();
            checkCRL(dp, paramsPKIXClone, cert, validDate, sign, workingPublicKey, certStatus, reasonsMask,
                    certPathCerts);
            validCrlFound = true;
        } catch (SimpleValidationErrorException e) {
            lastException = e;
        }
    }

    if (!validCrlFound)
        throw lastException;
    if (certStatus.getCertStatus() != CertStatus.UNREVOKED) {
        throw new SimpleValidationErrorException(ValidationErrorCode.certRevoked,
                new TrustedInput(certStatus.getRevocationDate()), crlReasons[certStatus.getCertStatus()]);
    }
    if (!reasonsMask.isAllReasons() && certStatus.getCertStatus() == CertStatus.UNREVOKED) {
        certStatus.setCertStatus(CertStatus.UNDETERMINED);
    }
    if (certStatus.getCertStatus() == CertStatus.UNDETERMINED) {
        throw new SimpleValidationErrorException(ValidationErrorCode.noValidCrlFound);
    }
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyTracingExtension.java

License:Open Source License

/**
 * Generates a new proxy tracing item from the URL.
 * //from  w ww .jav  a 2 s  .co m
 * @param url
 *                The URL to identify the issuer or the subject.
 */
public ProxyTracingExtension(String url) {
    name = new GeneralName(GeneralName.uniformResourceIdentifier, url);
    names = new GeneralNames(name);
}

From source file:eu.europa.ec.markt.dss.DSSUtils.java

License:Open Source License

/**
 * @param certificate//w  w  w  .  j  a va 2 s.  co m
 * @return
 */
public static IssuerSerial getIssuerSerial(final X509Certificate certificate) {

    final X500Name issuerX500Name = DSSUtils.getX509CertificateHolder(certificate).getIssuer();
    final GeneralName generalName = new GeneralName(issuerX500Name);
    final GeneralNames generalNames = new GeneralNames(generalName);
    final BigInteger serialNumber = certificate.getSerialNumber();
    final IssuerSerial issuerSerial = new IssuerSerial(generalNames, serialNumber);
    return issuerSerial;
}

From source file:eu.europa.esig.dss.DSSASN1Utils.java

License:Open Source License

/**
 * This method returns a new IssuerSerial based on the certificate token
 *
 * @param certToken/*  w  ww .  j  ava2  s.  c o  m*/
 *            the certificate token
 * @return a IssuerSerial
 */
public static IssuerSerial getIssuerSerial(final CertificateToken certToken) {
    final X500Name issuerX500Name = getX509CertificateHolder(certToken).getIssuer();
    final GeneralName generalName = new GeneralName(issuerX500Name);
    final GeneralNames generalNames = new GeneralNames(generalName);
    final BigInteger serialNumber = certToken.getCertificate().getSerialNumber();
    final IssuerSerial issuerSerial = new IssuerSerial(generalNames, serialNumber);
    return issuerSerial;
}

From source file:eu.optimis.ics.BrokerVPNCredentials.CACredentials.java

License:Open Source License

public X509CertificateHolder genCACertificate(KeyPair CAKP) throws CertIOException, NoSuchAlgorithmException {
    BigInteger serial = BigInteger.valueOf(42);

    Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365));

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(CAKP.getPublic().getEncoded());

    // Same issuer and subject for the self-signed CA certificate
    X500Name issuer = new X500Name(
            "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com");
    X500Name subject = new X500Name(
            "C=UK, ST=Suffolk, L=Ipswich, O=BT, OU=R&T, CN=CloudShadow, Name=Ali, emailAddress=ali.sajjad@bt.com");

    X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter,
            subject, publicKeyInfo);/*ww  w . j  a v  a  2  s .  c  om*/

    GeneralNames gNames = new GeneralNames(new GeneralName(issuer));
    v3CertBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
            new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKeyInfo));
    v3CertBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(publicKeyInfo, gNames, serial));
    v3CertBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));

    ContentSigner sigGen = null;

    try {
        sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(CAKP.getPrivate());
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }
    return v3CertBuilder.build(sigGen);
}