Example usage for org.bouncycastle.asn1 ASN1EncodableVector ASN1EncodableVector

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

Introduction

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

Prototype

public ASN1EncodableVector() 

Source Link

Usage

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 . j  a  va 2 s .c  om
 * @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  . ja  v  a2  s  .c  om*/
 */
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.peppol.as2.SMimeMessageFactory.java

License:EUPL

/** Creates an S/MIME message using the supplied MimeBodyPart. The signature is generated using the private key
 * as supplied in the constructor. Our certificate, which is required to verify the signature is enclosed.
 *//*from ww w.ja  v a  2  s  .  co  m*/
public MimeMessage createSignedMimeMessage(MimeBodyPart mimeBodyPart) {

    //
    // S/MIME capabilities are required, but we simply supply an empty vector
    //
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();

    //
    // create the generator for creating an smime/signed message
    //
    SMIMESignedGenerator smimeSignedGenerator = new SMIMESignedGenerator("binary"); //also see CMSSignedGenerator ?

    //
    // add a signer to the generator - this specifies we are using SHA1 and
    // adding the smime attributes above to the signed attributes that
    // will be generated as part of the signature. The encryption algorithm
    // used is taken from the key - in this RSA with PKCS1Padding
    //
    try {
        smimeSignedGenerator.addSignerInfoGenerator(
                new JcaSimpleSignerInfoGeneratorBuilder().setProvider(new BouncyCastleProvider())
                        .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                        .build("SHA1withRSA", privateKey, ourCertificate));
    } catch (OperatorCreationException e) {
        throw new IllegalStateException("Unable to add Signer information. " + e.getMessage(), e);
    } catch (CertificateEncodingException e) {
        throw new IllegalStateException(
                "Certificate encoding problems while adding signer information." + e.getMessage(), e);
    }

    //
    // add our pool of certs and crls (if any) to go with the signature
    //
    List certList = new ArrayList();
    certList.add(ourCertificate);

    //
    // create a CertStore containing the certificates we want carried
    // in the signature
    //
    Store certs = null;
    try {
        certs = new JcaCertStore(certList);
    } catch (CertificateEncodingException e) {
        throw new IllegalStateException("Unable to create JcaCertStore with our certificate. " + e.getMessage(),
                e);
    }
    smimeSignedGenerator.addCertificates(certs);

    //
    // Signs the supplied MimeBodyPart
    //
    MimeMultipart mimeMultipart = null;
    try {
        mimeMultipart = smimeSignedGenerator.generate(mimeBodyPart);
    } catch (SMIMEException e) {
        throw new IllegalStateException("Unable to generate signed mime multipart." + e.getMessage(), e);
    }

    //
    // Get a Session object and create the mail message
    //
    Properties props = System.getProperties();
    Session session = Session.getDefaultInstance(props, null);

    MimeMessage mimeMessage = new MimeMessage(session);

    try {
        mimeMessage.setContent(mimeMultipart, mimeMultipart.getContentType());
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to  set Content type of MimeMessage. " + e.getMessage(), e);
    }
    try {
        mimeMessage.saveChanges();
    } catch (MessagingException e) {
        throw new IllegalStateException("Unable to save changes to Mime message. " + e.getMessage(), e);
    }

    return mimeMessage;

}

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 {//w w w.j av a  2  s  .  c  o  m
        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  .  jav a2 s  .  c  o 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.  
 * //from   w ww . java 2  s.c om
 * @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);
    }
}

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);/*w w w.jav 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.aos.crypto.spl09.SignedMailExample.java

License:Apache License

public static MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert,
        CertStore certsAndCRLs, MimeBodyPart dataPart) throws Exception {
    // create some smime capabilities in case someone wants to respond
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();

    caps.addCapability(SMIMECapability.aES256_CBC);
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);

    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert)));

    // set up the generator
    SMIMESignedGenerator gen = new SMIMESignedGenerator();

    gen.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA256, new AttributeTable(signedAttrs), null);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed message
    return gen.generate(dataPart, "BC");
}

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);
}