Example usage for org.bouncycastle.asn1 ASN1EncodableVector add

List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector add

Introduction

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

Prototype

public void add(ASN1Encodable element) 

Source Link

Usage

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineB.java

License:Open Source License

private void addSigningCertificateAttribute(final CAdESSignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) throws DSSException {
    final DigestAlgorithm digestAlgorithm = parameters.getDigestAlgorithm();
    final byte[] encoded = parameters.getSigningCertificate().getEncoded();
    final byte[] certHash = DSSUtils.digest(digestAlgorithm, encoded);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding Certificate Hash {} with algorithm {}", Hex.encodeHexString(certHash),
                digestAlgorithm.getName());
    }/*  w  ww  . j a  v  a 2s .c o  m*/
    final IssuerSerial issuerSerial = DSSASN1Utils.getIssuerSerial(parameters.getSigningCertificate());

    Attribute attribute = null;
    if (digestAlgorithm == DigestAlgorithm.SHA1) {
        final ESSCertID essCertID = new ESSCertID(certHash, issuerSerial);
        SigningCertificate signingCertificate = new SigningCertificate(essCertID);
        attribute = new Attribute(id_aa_signingCertificate, new DERSet(signingCertificate));
    } else {
        final ESSCertIDv2 essCertIdv2 = new ESSCertIDv2(DSSASN1Utils.getAlgorithmIdentifier(digestAlgorithm),
                certHash, issuerSerial);
        SigningCertificateV2 signingCertificateV2 = new SigningCertificateV2(essCertIdv2);
        attribute = new Attribute(id_aa_signingCertificateV2, new DERSet(signingCertificateV2));
    }
    signedAttributes.add(attribute);
}

From source file:eu.europa.esig.dss.cades.signature.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

private Attribute getComposedAtsHashIndex(AlgorithmIdentifier algorithmIdentifiers,
        ASN1Sequence certificatesHashIndex, ASN1Sequence crLsHashIndex,
        ASN1Sequence unsignedAttributesHashIndex) {
    final ASN1EncodableVector vector = new ASN1EncodableVector();
    if (algorithmIdentifiers != null) {
        vector.add(algorithmIdentifiers);
    }// w  ww.  ja  va 2s  .  c  om
    vector.add(certificatesHashIndex);
    vector.add(crLsHashIndex);
    vector.add(unsignedAttributesHashIndex);
    final ASN1Sequence derSequence = new DERSequence(vector);
    return new Attribute(id_aa_ATSHashIndex, new DERSet(derSequence));
}

From source file:eu.europa.esig.dss.cades.signature.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

/**
 * The field certificatesHashIndex is a sequence of octet strings. Each one contains the hash value of one
 * instance of CertificateChoices within certificates field of the root SignedData. A hash value for
 * every instance of CertificateChoices, as present at the time when the corresponding archive time-stamp is
 * requested, shall be included in certificatesHashIndex. No other hash value shall be included in this field.
 *
 * @return/*  w ww . j av a2  s .  c  o  m*/
 * @throws eu.europa.esig.dss.DSSException
 */
private ASN1Sequence getCertificatesHashIndex() throws DSSException {

    final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector();

    final List<CertificateToken> certificateTokens = cadesSignature.getCertificates();
    for (final CertificateToken certificateToken : certificateTokens) {
        final byte[] encodedCertificate = certificateToken.getEncoded();
        final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encodedCertificate);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Adding to CertificatesHashIndex DSS-Identifier: {} with hash {}",
                    certificateToken.getDSSId(), Hex.encodeHexString(digest));
        }
        final DEROctetString derOctetStringDigest = new DEROctetString(digest);
        certificatesHashIndexVector.add(derOctetStringDigest);
    }
    return new DERSequence(certificatesHashIndexVector);
}

From source file:eu.europa.esig.dss.cades.signature.CadesLevelBaselineLTATimestampExtractor.java

License:Open Source License

private void digestAndAddToList(ASN1EncodableVector crlsHashIndex, byte[] encoded) {
    final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encoded);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding to crlsHashIndex with hash {}", Hex.encodeHexString(digest));
    }//w  w  w.  j av a 2s  . co m
    final DEROctetString derOctetStringDigest = new DEROctetString(digest);
    crlsHashIndex.add(derOctetStringDigest);
}

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  .java 2s. c o  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 w  ww.j ava2  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:fi.aalto.cs.drumbeat.CACertificateCreator.java

License:Open Source License

public X509Certificate createCACert(PublicKey publicKey, PrivateKey privateKey) {

    X509Certificate ca_cert = null;
    try {//from  ww  w.j a va2s  .  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:gov.nih.nci.cacis.nav.SendSignedMail.java

License:BSD License

private SMIMESignedGenerator createSigner(Certificate[] chain, PrivateKey privateKey) {
    final SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    final ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X509Name(((X509Certificate) chain[0]).getIssuerDN().getName()),
                    ((X509Certificate) chain[0]).getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    final SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSigner(privateKey, (X509Certificate) chain[0],
            "DSA".equals(privateKey.getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                    : SMIMESignedGenerator.DIGEST_MD5,
            new AttributeTable(attributes), null);

    return signer;
}

From source file:hk.hku.cecid.edi.as2.module.test.IncomingMessageProcessorTest.java

License:Open Source License

private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception {
    X509Certificate cert = partnershipDVO.getVerifyX509Certificate();

    /* Create the SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(
            new IssuerAndSerialNumber(new X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber())));
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.setContentTransferEncoding("base64");
    signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(),
            SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(attributes), null);

    // Add the list of certs to the generator
    ArrayList certList = new ArrayList();
    certList.add(cert);//from  w w  w  .java  2 s  . co m
    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    // Sign body part
    MimeMultipart mm = signer.generate(bodyPart, "BC");

    InternetHeaders headers = new InternetHeaders();
    boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true")).booleanValue();
    headers.setHeader("Content-Type",
            isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mm.writeTo(baos);
    MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

    return signedPart;
}

From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java

License:Open Source License

/**
 * Signs the encapsulated MIME body part.  
 * //w  w  w.  j av  a 2s.  c  o m
 * @return an S/MIME message encapsulating the signed MIME body part. 
 * @throws SMimeException if unable to sign the body part.
 */
public SMimeMessage sign() throws SMimeException {
    try {
        if (privateKey == null) {
            throw new SMimeException("Private key not found");
        }

        try {
            setDefaults();

            /* Create the SMIMESignedGenerator */
            SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
            capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
            capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
            capabilities.addCapability(SMIMECapability.dES_CBC);

            ASN1EncodableVector attributes = new ASN1EncodableVector();
            attributes.add(new SMIMEEncryptionKeyPreferenceAttribute(new IssuerAndSerialNumber(
                    new X509Name(cert.getIssuerDN().getName()), cert.getSerialNumber())));
            attributes.add(new SMIMECapabilitiesAttribute(capabilities));

            SMIMESignedGenerator signer = new SMIMESignedGenerator();
            signer.setContentTransferEncoding(getContentTransferEncoding());
            signer.addSigner(privateKey, cert, getDigestAlgorithm(), new AttributeTable(attributes), null);

            /* Add the list of certs to the generator */
            ArrayList certList = new ArrayList();
            certList.add(cert);
            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    SECURITY_PROVIDER);
            signer.addCertificatesAndCRLs(certs);

            /* Sign the body part */
            MimeMultipart mm = signer.generate(bodyPart, SECURITY_PROVIDER);

            InternetHeaders headers = new InternetHeaders();
            boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true"))
                    .booleanValue();
            headers.setHeader("Content-Type",
                    isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mm.writeTo(baos);
            MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

            return new SMimeMessage(signedPart, this);
        } catch (org.bouncycastle.mail.smime.SMIMEException ex) {
            throw new SMimeException(ex.getMessage(), ex.getUnderlyingException());
        }
    } catch (Exception e) {
        throw new SMimeException("Unable to sign body part", e);
    }
}