Example usage for org.bouncycastle.asn1 DERSequence DERSequence

List of usage examples for org.bouncycastle.asn1 DERSequence DERSequence

Introduction

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

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

From source file:ClientOCSPDriver.java

License:Open Source License

/**
 Method added to generate ASNSequence object of subjectDN consturcted in appropriate ASN1 type
 X509Name constructs all DN components as printablestring by default
         //from   w  w  w.ja v a 2 s  . c  om
 This code was taken and modified from X509Name.java file of BouncyCastle
 **/
public ASN1Sequence getASNSequence(Vector oids, Vector values) {
    ASN1Sequence seq;

    ASN1EncodableVector vec = new ASN1EncodableVector();
    ASN1EncodableVector sVec = new ASN1EncodableVector();
    DERObjectIdentifier lstOid = null;

    for (int i = 0; i != oids.size(); i++) {
        ASN1EncodableVector v = new ASN1EncodableVector();
        DERObjectIdentifier oid = (DERObjectIdentifier) oids.elementAt(i);

        v.add(oid);

        String str = (String) values.elementAt(i);

        v.add(getConvertedValue(oid, str));

        if (lstOid == null) {
            sVec.add(new DERSequence(v));
        } else {
            vec.add(new DERSet(sVec));
            sVec = new ASN1EncodableVector();
            sVec.add(new DERSequence(v));
        }

        lstOid = oid;
    }

    vec.add(new DERSet(sVec));

    seq = new DERSequence(vec);

    return seq;
}

From source file:be.fedict.trust.test.PKITestUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        DateTime notBefore, DateTime notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey,
        boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage,
        String signatureAlgorithm, boolean tsa, boolean includeSKID, boolean includeAKID,
        PublicKey akidPublicKey, String certificatePolicy, Boolean qcCompliance, boolean ocspResponder,
        boolean qcSSCD) throws IOException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, OperatorCreationException {

    X500Name issuerName;//from   www  .  j  a  v a 2 s  .co  m
    if (null != issuerCertificate) {
        issuerName = new X500Name(issuerCertificate.getSubjectX500Principal().toString());
    } else {
        issuerName = new X500Name(subjectDn);
    }
    X500Name subjectName = new X500Name(subjectDn);
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
    if (includeSKID) {
        x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                extensionUtils.createSubjectKeyIdentifier(subjectPublicKey));
    }

    if (includeAKID) {

        PublicKey authorityPublicKey;
        if (null != akidPublicKey) {
            authorityPublicKey = akidPublicKey;
        } else if (null != issuerCertificate) {
            authorityPublicKey = issuerCertificate.getPublicKey();
        } else {
            authorityPublicKey = subjectPublicKey;
        }
        x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extensionUtils.createAuthorityKeyIdentifier(authorityPublicKey));
    }

    if (caFlag) {
        if (-1 == pathLength) {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(2147483647));
        } else {
            x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true,
                    new BasicConstraints(pathLength));
        }
    }

    if (null != crlUri) {
        GeneralName generalName = new GeneralName(GeneralName.uniformResourceIdentifier,
                new DERIA5String(crlUri));
        GeneralNames generalNames = new GeneralNames(generalName);
        DistributionPointName distPointName = new DistributionPointName(generalNames);
        DistributionPoint distPoint = new DistributionPoint(distPointName, null, null);
        DistributionPoint[] crlDistPoints = new DistributionPoint[] { distPoint };
        CRLDistPoint crlDistPoint = new CRLDistPoint(crlDistPoints);
        x509v3CertificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistPoint);
    }

    if (null != ocspUri) {
        GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        x509v3CertificateBuilder.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, keyUsage);
    }

    if (null != certificatePolicy) {
        ASN1ObjectIdentifier policyObjectIdentifier = new ASN1ObjectIdentifier(certificatePolicy);
        PolicyInformation policyInformation = new PolicyInformation(policyObjectIdentifier);
        x509v3CertificateBuilder.addExtension(Extension.certificatePolicies, false,
                new DERSequence(policyInformation));
    }

    if (null != qcCompliance) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        if (qcCompliance) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcCompliance));
        } else {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_RetentionPeriod));
        }
        if (qcSSCD) {
            vec.add(new QCStatement(QCStatement.id_etsi_qcs_QcSSCD));
        }
        x509v3CertificateBuilder.addExtension(Extension.qCStatements, true, new DERSequence(vec));

    }

    if (tsa) {
        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));
    }

    if (ocspResponder) {
        x509v3CertificateBuilder.addExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nocheck, false,
                DERNull.INSTANCE);

        x509v3CertificateBuilder.addExtension(Extension.extendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_OCSPSigning));
    }

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(issuerPrivateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

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

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public byte[] buildCmsBody(String signedHashId, X509Certificate certContent, byte[] content, String hashId,
        int version) throws CertificateEncodingException, IOException {
    final ASN1EncodableVector whole = new ASN1EncodableVector();
    whole.add(new DERObjectIdentifier(CMS_SIGNED_ID));

    final ASN1EncodableVector body = new ASN1EncodableVector();
    // ----- versao -------
    // final int version = 1;
    body.add(new DERInteger(version));
    buildDigestAlg(body, hashId);// w w w . ja va 2s . c o m
    // buildContentInfo(body, content);
    buildCerts(body, certContent);

    buildSignerInfo(body, signedHashId, certContent, hashId);

    whole.add(new DERTaggedObject(0, new DERSequence(body)));

    return genOutput(new DERSequence(whole));

}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public byte[] buildCmsBody(byte[] signedHashId, X509Certificate certContent, List<X509Certificate> chain,
        int hashId, int version, int attachSize) throws Exception {
    final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
    whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ

    final ASN1EncodableVector body = new ASN1EncodableVector();
    // ----- versao -------
    // final int version = 1;
    body.add(new DERInteger(version)); // 3 INT
    buildDigestAlg(body, getHashAlg(hashId)); // 3 SET
    buildContentInfo(body, attachSize); // 3 SEQ
    buildCerts(body, chain); // 3 CS

    buildSignerInfo(body, signedHashId, certContent, hashId); // 3 SET

    whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
            body))); // 1 CS

    return genOutput(new DERSequence(whole));

}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

public byte[] buildADRBBody(List<AppSignedInfoEx> listAsiEx, SignPolicy signPol, List<X509Certificate> chain,
        int version, boolean signingCertFallback, int attachSize) throws Exception {
    // AppSignedInfoEx asiEx = listAsiEx.get(0);
    final ASN1EncodableVector whole = new ASN1EncodableVector(); // 0 SEQ
    whole.add(new DERObjectIdentifier(CMS_SIGNED_ID)); // 1 SEQ

    final ASN1EncodableVector body = new ASN1EncodableVector();
    // ----- versao -------
    // final int version = 1;
    body.add(new DERInteger(version)); // 3 INT

    List<String> listHashId = createHashList(listAsiEx);
    buildDigestAlg(body, listHashId); // 3 SET

    buildContentInfo(body, attachSize); // 3 SEQ
    if (chain != null) {
        buildCerts(body, chain); // 3 CS
    } else {//from   w  w  w .ja  v  a2 s . c om
        buildCertsASIE(body, listAsiEx); // 3 CS
    }

    // buildADRBSignerInfo(body, asiEx.getSignedHash(), asiEx.getX509(),
    // asiEx.getOrigHash(), signPol.getPolicyHash(),
    // asiEx.getCertHash(), asiEx.getSigningTime(),
    // asiEx.getIdSha(), signPol.getPolicyUri(),
    // signPol.getPolicyId(),
    // signingCertFallback); // 3 SET

    buildADRBSignerInfo(body, listAsiEx, signPol, signingCertFallback); // 3
    // SET

    whole.add(new DERTaggedObject(0, new DERSequence( // 2 SEQ
            body))); // 1 CS

    return genOutput(new DERSequence(whole));

}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private void buildSignerInfo(ASN1EncodableVector body, byte[] signedHashContent, X509Certificate certContent,
        int hashId) throws Exception {
    // ----- Signers Info --------

    final ASN1EncodableVector vec = new ASN1EncodableVector();
    final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
    signerinfoVector.add(new DERInteger(SI_VERSION));

    signerinfoVector.add(siAddCert(certContent));
    signerinfoVector.add(siAddDigestAlgorithm(getHashAlg(hashId)));
    signerinfoVector.add(siAddDigestEncryptionAlgorithm(getHashSignAlg(hashId)));
    // Add the digest
    signerinfoVector.add(new DEROctetString(signedHashContent));

    final DERSequence siSeq = new DERSequence(signerinfoVector);
    vec.add(siSeq);/*from  w w w. j av a 2  s .  c  om*/
    DERSet siSet = new DERSet(vec);
    body.add(siSet);

}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private void buildADRBSignerInfo(ASN1EncodableVector body, List<AppSignedInfoEx> listAsiEx, SignPolicy signPol,
        boolean signingCertFallback) throws Exception {
    final ASN1EncodableVector vec = new ASN1EncodableVector();
    // DERSequence siSeq = null;

    // ----- Signers Info --------
    for (AppSignedInfoEx next : listAsiEx) {
        final ASN1EncodableVector signerinfoVector = new ASN1EncodableVector();
        String hashId = getHashAlg(next.getIdSha());
        String hashSignId = getHashSignAlg(next.getIdSha());

        signerinfoVector.add(new DERInteger(SI_VERSION));

        signerinfoVector.add(siAddCert(next.getX509()));
        signerinfoVector.add(siAddDigestAlgorithm(hashId));
        // der encoded structure
        DERTaggedObject derEncStruct = adrbSiCreateDerEncSigned(next.getOrigHash(), signPol.getPolicyHash(),
                next.getCertHash(), next.getX509(), next.getSigningTime(), next.getIdSha(),
                signPol.getPolicyUri(), signPol.getPolicyId(), signingCertFallback);
        signerinfoVector.add(derEncStruct);

        signerinfoVector.add(siAddDigestEncryptionAlgorithm(hashSignId));
        // Add the digest
        signerinfoVector.add(new DEROctetString(next.getSignedHash()));

        final DERSequence siSeq = new DERSequence(signerinfoVector);
        vec.add(siSeq);//from  w  ww. j  a  v  a  2 s.  c o m
    }
    // ----- Signers Info --------

    DERSet siSet = new DERSet(vec);
    body.add(siSet);

}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private DERSequence siCreateDerEncSeqADRB(byte[] origHash, byte[] polHash, byte[] certHash,
        X509Certificate cert, Date now, int hashNdx, String sigPolicyUri, String sigPolicyId,
        boolean signingCertFallback) throws Exception {
    String hashId = getHashAlg(hashNdx);
    final ASN1EncodableVector desSeq = new ASN1EncodableVector();

    // As assinaturas feitas segundo esta PA definem como obrigatrios as
    // seguintes atributos
    // assinados:
    // a) id-contentType;
    // b) id-messageDigest;
    // c.1) Para as verses 1.0, 1.1 e 2.0, id-aa-signingCertificate;
    // c.2) A partir da verso 2.1, inclusive, id-aa-signingCertificateV2;
    // d) id-aa-ets-sigPolicyId.

    // OPTIONAL//from  w ww  . j  a  v a2  s .  c  om
    // private static final String ID_SIGNING_TIME = "1.2.840.113549.1.9.5";
    if (now != null) {
        Attribute seq3 = createSigningTime(now);
        desSeq.add(seq3);
    }

    // D
    // private static final String ID_SIG_POLICY =
    // "1.2.840.113549.1.9.16.2.15";

    if (polHash != null && sigPolicyUri != null && sigPolicyId != null) {
        Attribute seq2 = createPolicyId(polHash, hashId, sigPolicyUri, sigPolicyId);
        desSeq.add(seq2);
    }

    // C
    // private static final String ID_SIGNING_CERT2 =
    // "1.2.840.113549.1.9.16.2.47";
    if (certHash != null && cert != null) {
        Attribute seq1 = createCertRef(certHash, cert, signingCertFallback, hashNdx);
        desSeq.add(seq1);
    }

    // B
    // private static final String ID_MESSAGE_DIGEST =
    // "1.2.840.113549.1.9.4";
    if (origHash != null) {
        Attribute seq4 = createMessageDigest(origHash);
        desSeq.add(seq4);
    }

    // A
    // private static final String ID_CONTENT_TYPE = "1.2.840.113549.1.9.3";
    Attribute seq5 = createContentType();
    desSeq.add(seq5);

    DERSequence seq00 = new DERSequence(desSeq);
    return seq00;
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private Attribute createPolicyId(byte[] polHash, String polHashAlg, String sigPolicyUri, String sigPolicyId) {

    final ASN1EncodableVector desSeq12 = new ASN1EncodableVector();
    desSeq12.add(new DERObjectIdentifier(polHashAlg));
    DERSequence seq12 = new DERSequence(desSeq12);

    final ASN1EncodableVector desSeq1 = new ASN1EncodableVector();
    desSeq1.add(seq12);/*w  ww . ja  v  a2 s .c  o m*/
    desSeq1.add(new DEROctetString(polHash));
    DERSequence seq1 = new DERSequence(desSeq1);

    // // end seq 1

    // IGUALAR AO ITAU

    final ASN1EncodableVector desSeq22 = new ASN1EncodableVector();
    desSeq22.add(new DERObjectIdentifier(ID_SIG_POLICY_URI));
    desSeq22.add(new DERIA5String(sigPolicyUri));
    DERSequence seq22 = new DERSequence(desSeq22);

    final ASN1EncodableVector desSeq2 = new ASN1EncodableVector();
    desSeq2.add(seq22);

    DERSequence seq2 = new DERSequence(desSeq2);

    final ASN1EncodableVector aevDSet1 = new ASN1EncodableVector();
    final ASN1EncodableVector aevDSeq1 = new ASN1EncodableVector();
    aevDSeq1.add(new DERObjectIdentifier(sigPolicyId));
    aevDSeq1.add(seq1);

    aevDSeq1.add(seq2);

    DERSequence dsq1 = new DERSequence(aevDSeq1);
    aevDSet1.add(dsq1);
    DERSet ds1 = new DERSet(aevDSet1);

    Attribute ret = new Attribute(new ASN1ObjectIdentifier(ID_SIG_POLICY), ds1);
    return ret;
}

From source file:bluecrystal.bcdeps.helper.DerEncoder.java

License:Open Source License

private Attribute createCertRef(byte[] certHash, X509Certificate certContent, boolean signingCertFallback,
        int hashId) throws Exception {
    // *** BEGIN ***

    // 5.2.1.1.3 Certificados Obrigatoriamente Referenciados
    // O atributo signingCertificate deve conter referncia apenas ao
    // certificado do signatrio.

    // 5.2.1.1.4 Certificados Obrigatrios do Caminho de Certificao
    // Para a verso 1.0: nenhum certificado
    // Para as verses 1.1, 2.0 e 2.1: o certificado do signatrio.

    // ESSCertIDv2 ::= SEQUENCE {
    // hashAlgorithm AlgorithmIdentifier
    // DEFAULT {algorithm id-sha256},
    // certHash Hash,
    // issuerSerial IssuerSerial OPTIONAL
    // }/* w w w .  j  a va2s  .co  m*/
    //
    // Hash ::= OCTET STRING
    //
    // IssuerSerial ::= SEQUENCE {
    // issuer GeneralNames,
    // serialNumber CertificateSerialNumber
    // }
    final ASN1EncodableVector issuerSerialaev = new ASN1EncodableVector();

    final ASN1EncodableVector issuerCertaev = new ASN1EncodableVector();

    DERTaggedObject issuerName = new DERTaggedObject(true, 4, // issuer
            // GeneralNames,
            getEncodedIssuer(certContent.getTBSCertificate()));

    // DERTaggedObject issuerName = new DERTaggedObject(false, 0, // issuer
    // GeneralNames,
    // getEncodedIssuer(certContent.getTBSCertificate()));
    issuerCertaev.add(issuerName);

    DERSequence issuerCertseq = new DERSequence(issuerCertaev); // IssuerSerial
    // ::=
    // SEQUENCE
    // {
    issuerSerialaev.add(issuerCertseq);

    // serialNumber CertificateSerialNumber
    BigInteger serialNumber = certContent.getSerialNumber();
    issuerSerialaev.add(new DERInteger(serialNumber));

    DERSequence issuerSerial = new DERSequence(issuerSerialaev);
    // *** END ***

    final ASN1EncodableVector essCertIDv2aev = new ASN1EncodableVector();
    essCertIDv2aev.add(new DEROctetString(certHash)); // Hash ::= OCTET
    // STRING

    essCertIDv2aev.add(issuerSerial); // ESSCertIDv2 ::= SEQUENCE {

    // hashAlgorithm AlgorithmIdentifier

    if (!((signingCertFallback && hashId == NDX_SHA1) || (!signingCertFallback && hashId == NDX_SHA256))) {
        DERObjectIdentifier hashAlgorithm = new DERObjectIdentifier(getHashAlg(hashId));
        essCertIDv2aev.add(hashAlgorithm);
    }
    // Nota 4: Para o atributo ESSCertIDv2, utilizada nas verses 2.1 das
    // polticas de assinatura
    // baseadas em CAdES, as aplicaes NO DEVEM codificar o campo
    // hashAlgorithm caso
    // utilize o mesmo algoritmo definido como valor default (SHA-256),
    // conforme ISO 8825-1.

    DERSequence essCertIDv2seq = new DERSequence(essCertIDv2aev);

    // ************************************************************************
    //
    final ASN1EncodableVector aevSeq3 = new ASN1EncodableVector();
    aevSeq3.add(essCertIDv2seq);
    DERSequence seq3 = new DERSequence(aevSeq3);

    final ASN1EncodableVector aevSeq2 = new ASN1EncodableVector();
    aevSeq2.add(seq3);
    DERSequence seq2 = new DERSequence(aevSeq2);

    final ASN1EncodableVector aevSet = new ASN1EncodableVector();
    aevSet.add(seq2);
    ASN1Set mainSet = new DERSet(aevSet);

    Attribute seq1 = new Attribute(
            new ASN1ObjectIdentifier(signingCertFallback ? ID_SIGNING_CERT : ID_SIGNING_CERT2), mainSet);
    return seq1;
}