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:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * The value of the messageImprint field within TimeStampToken shall be a
 * hash of the concatenation of:  the encapContentInfo element of the
 * SignedData sequence;  any external content being protected by the
 * signature, if the eContent element of the encapContentInfo is omitted; 
 * the Certificates and crls elements of the SignedData sequence, when
 * present; and  all data elements in the SignerInfo sequence including all
 * signed and unsigned attributes.//w w w  .j a va 2  s .co  m
 * NOTE 1: An alternative archiveTimestamp attribute, identified by an
 * object identifier { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
 * pkcs-9(9) smime(16) id-aa(2) 27, is defined in prior versions of TS 101
 * 733. The archiveTimestamp attribute, defined in versions of TS 101 733
 * prior to 1.5.1, is not compatible with the attribute defined in the
 * present document. The archiveTimestamp attribute, defined in versions
 * 1.5.1 to 1.6.3 of TS 101 733, is compatible with the present document if
 * the content is internal to encapContentInfo. Unless the version of TS 101
 * 733 employed by the signing party is known by all recipients, use of the
 * archiveTimestamp attribute defined in prior versions of TS 101 733 is
 * deprecated. NOTE 2: Counter signatures held as countersignature
 * attributes do not require independent archive time-stamps as they are
 * protected by the archive time-stamp against the containing SignedData
 * structure. NOTE 3: Unless DER is used throughout, it is recommended that
 * the binary encoding of the ASN.1 structures being time-stamped be
 * preserved when being archived to ensure that the recalculation of the
 * data hash is consistent. NOTE 4: The hash is calculated over the
 * concatenated data elements as received /stored including the Type and
 * Length encoding. NOTE 5: Whilst it is recommended that unsigned
 * attributes be DER encoded, it cannot generally be so guaranteed except by
 * prior arrangement.
 *
 * @param timestampToken
 * @return
 * @throws DSSException
 */
private byte[] getArchiveTimestampDataV2(TimestampToken timestampToken) throws DSSException {

    try {

        final ByteArrayOutputStream data = new ByteArrayOutputStream();

        final ContentInfo contentInfo = cmsSignedData.toASN1Structure();
        final SignedData signedData = SignedData.getInstance(contentInfo.getContent());

        ContentInfo content = signedData.getEncapContentInfo();
        if ((content == null) || (content.getContent() == null)) {
            /*
             * Detached signatures have either no encapContentInfo in
             * signedData, or it exists but has no eContent
             */
            if (getOriginalDocumentStream() != null) {
                data.write(content.toASN1Primitive().getEncoded());
                IOUtils.copy(getOriginalDocumentStream(), data);
            } else {
                throw new DSSException("Signature is detached and no original data provided.");
            }
        } else {

            ASN1OctetString octet = (ASN1OctetString) content.getContent();

            ContentInfo info2 = new ContentInfo(PKCSObjectIdentifiers.data, octet);
            final byte[] contentInfoBytes = info2.getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
            }
            data.write(contentInfoBytes);
        }
        final ASN1Set certificates = signedData.getCertificates();
        if (certificates != null) {

            final byte[] certificatesBytes = new DERTaggedObject(false, 0,
                    new DERSequence(certificates.toArray())).getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
            }
            data.write(certificatesBytes);
        }
        if (signedData.getCRLs() != null) {

            final byte[] crlBytes = signedData.getCRLs().getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
            }
            data.write(crlBytes);
        }
        final SignerInfo signerInfo = signerInformation.toASN1Structure();
        final ByteArrayOutputStream signerByteArrayOutputStream = new ByteArrayOutputStream();
        final ASN1Set unauthenticatedAttributes = signerInfo.getUnauthenticatedAttributes();
        final ASN1Sequence filteredUnauthenticatedAttributes = filterUnauthenticatedAttributes(
                unauthenticatedAttributes, timestampToken);
        final ASN1Sequence asn1Object = getSignerInfoEncoded(signerInfo, filteredUnauthenticatedAttributes);
        for (int ii = 0; ii < asn1Object.size(); ii++) {

            final byte[] signerInfoBytes = DSSASN1Utils
                    .getDEREncoded(asn1Object.getObjectAt(ii).toASN1Primitive());
            signerByteArrayOutputStream.write(signerInfoBytes);
        }
        final byte[] signerInfoBytes = signerByteArrayOutputStream.toByteArray();
        if (LOG.isTraceEnabled()) {
            LOG.trace("SignerInfoBytes: {}", DSSUtils.toHex(signerInfoBytes));
        }
        data.write(signerInfoBytes);

        final byte[] result = data.toByteArray();
        return result;

    } catch (IOException e) {
        throw new DSSException(e);
    } catch (Exception e) {
        // When error in computing or in format the algorithm just
        // continues.
        LOG.warn("When error in computing or in format the algorithm just continue...", e);
        return DSSUtils.EMPTY_BYTE_ARRAY;
    }
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * Copied from org.bouncycastle.asn1.cms.SignerInfo#toASN1Object() and
 * adapted to be able to use the custom unauthenticatedAttributes
 *
 * @param signerInfo//from   w  w  w . ja  v a 2  s  .co  m
 * @param signerInfo
 * @param unauthenticatedAttributes
 * @return
 */
private ASN1Sequence getSignerInfoEncoded(final SignerInfo signerInfo,
        final ASN1Encodable unauthenticatedAttributes) {

    ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(signerInfo.getVersion());
    v.add(signerInfo.getSID());
    v.add(signerInfo.getDigestAlgorithm());

    final DERTaggedObject signedAttributes = CMSUtils.getDERSignedAttributes(signerInformation);
    if (signedAttributes != null) {
        v.add(signedAttributes);
    }

    v.add(signerInfo.getDigestEncryptionAlgorithm());
    v.add(signerInfo.getEncryptedDigest());

    if (unauthenticatedAttributes != null) {
        v.add(new DERTaggedObject(false, 1, unauthenticatedAttributes));
    }

    return new DERSequence(v);
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * Remove any archive-timestamp-v2/3 attribute added after the
 * timestampToken//from ww w. j a  va2 s.com
 */
private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes,
        TimestampToken timestampToken) {
    ASN1EncodableVector result = new ASN1EncodableVector();
    for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) {

        final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii));
        final ASN1ObjectIdentifier attrType = attribute.getAttrType();
        if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) {
            try {

                TimeStampToken token = new TimeStampToken(new CMSSignedData(DSSASN1Utils
                        .getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive())));
                if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
                    continue;
                }
            } catch (Exception e) {
                throw new DSSException(e);
            }
        }
        result.add(unauthenticatedAttributes.getObjectAt(ii));
    }
    return new DERSequence(result);
}

From source file:eu.europa.esig.dss.x509.crl.CRLToken.java

License:Open Source License

/**
 * @return the a copy of x509crl as a X509CRLHolder
 *///  w w w .  j  a  va 2  s .  c om
public X509CRLHolder getX509CrlHolder() {

    try {

        final X509CRL x509crl = getX509crl();
        final TBSCertList tbsCertList = TBSCertList.getInstance(x509crl.getTBSCertList());
        final AlgorithmIdentifier sigAlgOID = new AlgorithmIdentifier(
                new ASN1ObjectIdentifier(x509crl.getSigAlgOID()));
        final byte[] signature = x509crl.getSignature();
        final DERSequence seq = new DERSequence(
                new ASN1Encodable[] { tbsCertList, sigAlgOID, new DERBitString(signature) });
        final CertificateList x509CRL = new CertificateList(seq);
        // final CertificateList x509CRL = new
        // CertificateList.getInstance((Object)seq);
        final X509CRLHolder x509crlHolder = new X509CRLHolder(x509CRL);
        return x509crlHolder;
    } catch (CRLException e) {
        throw new DSSException(e);
    }
}

From source file:fi.aalto.cs.drumbeat.CACertificateCreator.java

License:Open Source License

public X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) {

    X509Certificate ca_cert = null;
    try {/*from  w w w. j a v a  2 s  .  c  om*/
        X500Name issuerName = new X500Name("CN=" + data_store.getCa_certificate().getCommon_name() + ", O="
                + data_store.getCa_certificate().getOrganization() + ", L="
                + data_store.getCa_certificate().getCity() + ", ST="
                + data_store.getCa_certificate().getCountry().getCountry_Name() + ", C="
                + data_store.getCa_certificate().getCountry().getCountry_Code());
        X500Name subjectName = issuerName;
        BigInteger serial = BigInteger.valueOf(new Random().nextInt());
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial,
                CertificateCommons.NOT_BEFORE, CertificateCommons.NOT_AFTER, subjectName, publicKey);
        builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(publicKey));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

        KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature
                | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
        builder.addExtension(Extension.keyUsage, false, usage);

        ASN1EncodableVector purposes = new ASN1EncodableVector();
        purposes.add(KeyPurposeId.id_kp_serverAuth);
        purposes.add(KeyPurposeId.id_kp_clientAuth);
        purposes.add(KeyPurposeId.anyExtendedKeyUsage);
        builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

        ca_cert = signCertificate(builder, privateKey);
        ca_cert.checkValidity(new Date());
        ca_cert.verify(publicKey);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return ca_cert;
}

From source file:fi.aalto.cs.drumbeat.ClientCertificateCreator.java

License:Open Source License

public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException {
    if (!sans.isEmpty()) {
        ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans.size()]);
        certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables));
    }//from  w ww . j  av a  2 s.  c  om
}

From source file:g4mfs.impl.org.peertrust.security.credentials.CryptTools.java

License:Open Source License

/**
 * Generate a Certificate that holds a Credential as a critical Extension in it.
 * @param pubKey the public key of the subject of the credential. This
 * is needed to create a valid X509Certificate and might be usefull to
 * improve security, when a public key infrastructure is used in this
 * prototype environment.//from  w ww. jav a  2 s .  c o m
 * @param subject the distinguished name of the subject of this 
 * credential. Important: There exists a certain format for distinguished 
 * names. For example "CN=alice" is a valid DN.
 * @param credential the String Representation of the credential
 * @param issuer the name of the signer of the credential. This should
 * be the person the caPrivKey belongs to.
 * @param caPrivKey the key that is used to sign the credential
 * @return A X.509Certificate 
 */
public static X509Certificate createCert(String subject, String credential, PublicKey pubKey, String issuer,
        PrivateKey caPrivKey) throws Exception {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // create the certificate - version 3 (only v3 allows usage of extensions)
    v3CertGen.reset();
    // TODO: Eindeutige Serialno
    v3CertGen.setSerialNumber(java.math.BigInteger.valueOf(3));
    v3CertGen.setIssuerDN(new X509Principal(issuer));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setSubjectDN(new X509Principal(subject));
    v3CertGen.setPublicKey(pubKey);
    v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    // add the extensions
    // - the credential as an extension
    //   - try to create a "SubjectAlternativeName" Extension in the othername field
    //     - create an OtherName (there is no OtherName class, so I have to improvise)
    int tag = 2; // Tag-Class 'Universal', BIT STRING: 2(works fine), OCTET STRING: 3
    DERObject derO = new DERPrintableString(credential);

    //     - create a GeneralName
    GeneralName gn = new GeneralName(derO, tag);

    //     - create a GeneralNames set of it:
    DERSequence ders = new DERSequence(gn);
    GeneralNames gns = new GeneralNames(ders);

    v3CertGen.addExtension(X509Extensions.SubjectAlternativeName, true, gns);

    // generate the cert
    X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey);

    // Testing:
    cert.checkValidity(new Date());

    return cert;
}

From source file:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Generate a X509 certificate for the given keypair.
 * The distinguished names must be in format: CN=cName, OU=orgUnit, O=org, L=city, S=state, C=countryCode
 * use backslash to escape a comma/*from   www.  j ava 2  s . co m*/
 * @param keypair the keypair
 * @param months the validity length in months
 * @param issuerDN the issuer distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param subjectDN the subject distinguished name: "CN=David Karnok,OU=EMI,O=MTA SZTAKI"
 * @param domain domain of the server to store in the subject alternative name extension
 * @param signAlgorithm the signing algorithm to use
 * @return the generated X509 certificate
 */
public X509Certificate createX509Certificate(KeyPair keypair, int months, String issuerDN, String subjectDN,
        String domain, String signAlgorithm) {
    try {
        // calendar for date calculations
        GregorianCalendar cal = new GregorianCalendar();

        // extract keypair components
        PublicKey pubKey = keypair.getPublic();
        PrivateKey privKey = keypair.getPrivate();

        // generate a random serial number
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(System.currentTimeMillis());
        byte[] serialNo = new byte[8];
        random.nextBytes(serialNo);
        BigInteger serial = new BigInteger(serialNo).abs();

        // create the certificate generator
        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        certGen.reset();

        // set certificate attributes
        certGen.setSerialNumber(serial);
        cal.setTimeInMillis(System.currentTimeMillis());
        certGen.setNotBefore(cal.getTime());
        cal.add(GregorianCalendar.MONTH, months);
        certGen.setNotAfter(cal.getTime());
        certGen.setPublicKey(pubKey);
        certGen.setSignatureAlgorithm(signAlgorithm);
        certGen.setIssuerDN(new X509Name(issuerDN));
        certGen.setSubjectDN(new X509Name(subjectDN));

        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));

        // create subject alternative name
        boolean isCritical = subjectDN == null || "".equals(subjectDN.trim());
        DERSequence othernameSeq = new DERSequence(
                new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                        new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
        GeneralName othernameGen = new GeneralName(GeneralName.otherName, othernameSeq);
        GeneralNames subjectAlternatives = new GeneralNames(othernameGen);
        certGen.addExtension(X509Extensions.SubjectAlternativeName, isCritical, subjectAlternatives);

        // finally generate the certificate
        X509Certificate cert = certGen.generateX509Certificate(privKey, BC_PROVIDER.getName(),
                new SecureRandom());
        cert.checkValidity(new Date());
        cert.verify(pubKey);

        return cert;
    } catch (NoSuchAlgorithmException ex) {
        throw new KeystoreFault(ex);
    } catch (CertificateException ex) {
        throw new KeystoreFault(ex);
    } catch (SignatureException ex) {
        throw new KeystoreFault(ex);
    } catch (NoSuchProviderException ex) {
        throw new KeystoreFault(ex);
    } catch (InvalidKeyException ex) {
        throw new KeystoreFault(ex);
    }
}

From source file:io.aos.crypto.spl05.MyStructure.java

License:Apache License

public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();

    if (version.getValue().intValue() != 0) {
        v.add(version);//from   w  w w . j  av  a 2  s.  co  m
    }

    v.add(created);
    v.add(baseData);

    if (extraData != null) {
        v.add(new DERTaggedObject(false, 0, extraData));
    }

    if (commentData != null) {
        v.add(new DERTaggedObject(false, 1, commentData));
    }

    return new DERSequence(v);
}

From source file:io.kodokojo.commons.utils.ssl.SSLUtils.java

License:Open Source License

private static void addASN1AndKeyUsageExtensions(JcaX509v3CertificateBuilder certificateBuilder)
        throws CertIOException {
    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

    KeyUsage keyUsage = new KeyUsage(
            keyCertSign | digitalSignature | keyEncipherment | dataEncipherment | cRLSign);
    certificateBuilder.addExtension(Extension.keyUsage, false, keyUsage);
}