Example usage for org.bouncycastle.asn1.cms Attribute Attribute

List of usage examples for org.bouncycastle.asn1.cms Attribute Attribute

Introduction

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

Prototype

public Attribute(ASN1ObjectIdentifier attrType, ASN1Set attrValues) 

Source Link

Usage

From source file:CreateSignature.java

License:Apache License

/**
 * We are extending CMS Signature/*w  w  w .  j  av a2s  .  c o m*/
 *
 * @param signer information about signer
 * @return information about SignerInformation
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = getTsaClient().getTimeStampToken(signer.getSignature());
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));

    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);

    SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer,
            new AttributeTable(signedAttributes));

    // TODO can this actually happen?
    if (newSigner == null) {
        return signer;
    }

    return newSigner;
}

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

License:Open Source License

private Attribute createContentType() {
    // // final ASN1EncodableVector desSeq = new ASN1EncodableVector();
    // // desSeq.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
    final ASN1EncodableVector setEV = new ASN1EncodableVector();
    setEV.add(new DERObjectIdentifier(ID_PKCS7_DATA));

    DERSet set = new DERSet(setEV);
    // // desSeq.add(set);
    // // DERSequence seq = new DERSequence(desSeq);
    Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(ID_CONTENT_TYPE), set);
    return seq1;/*from  ww  w.  j a v  a 2s. c  om*/
}

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

License:Open Source License

private Attribute createMessageDigest(byte[] origHash) {
    final ASN1EncodableVector setEV = new ASN1EncodableVector();
    setEV.add(new DEROctetString(origHash));

    DERSet set = new DERSet(setEV);

    Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(ID_MESSAGE_DIGEST), set);
    return seq1;// www .ja  v  a 2s .com
}

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

License:Open Source License

private Attribute createSigningTime(Date now) {
    final ASN1EncodableVector setEV = new ASN1EncodableVector();
    setEV.add(new DERUTCTime(now));

    DERSet set = new DERSet(setEV);
    Attribute seq1 = new Attribute(new ASN1ObjectIdentifier(ID_SIGNING_TIME), set);
    return seq1;//from w w  w  . ja v  a  2s  . c  om
}

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);/*from w w w . j ava 2  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
    // }/*www.ja  va2 s . c o 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;
}

From source file:br.gov.jfrj.siga.cd.TimeStamper.java

License:Open Source License

/**
 * Modyfy PKCS#7 data by adding timestamp
 * /*w  w w .  ja  v  a 2 s. c  o  m*/
 * (at) param signedData (at) throws Exception
 */
public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception {
    Collection ss = signedData.getSignerInfos().getSigners();
    SignerInformation si = (SignerInformation) ss.iterator().next();
    TimeStampToken tok = getTimeStampToken(si.getSignature());

    //      CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC");
    Store certs = tok.getCertificates();
    Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs);

    CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls,
            certsAndCrls, certsAndCrls);

    tok = new TimeStampToken(cmssdcrl);

    ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded());
    ASN1Primitive tstDER = asn1InputStream.readObject();
    DERSet ds = new DERSet(tstDER);
    Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds);
    ASN1EncodableVector dv = new ASN1EncodableVector();
    dv.add(a);
    AttributeTable at = new AttributeTable(dv);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    ss.clear();
    ss.add(si);
    SignerInformationStore sis = new SignerInformationStore(ss);
    signedData = CMSSignedData.replaceSigners(signedData, sis);
    return signedData;
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[])}.
 *
 * @param secondDigest the content digest
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 *///from   w ww . ja  v  a  2 s .co m
private DERSet getAuthenticatedAttributeSet(byte[] secondDigest, byte[] ocsp, Collection<byte[]> crlBytes,
        PdfSigner.CryptoStandard sigtype) {
    try {
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE));
        v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        boolean haveCrl = false;
        if (crlBytes != null) {
            for (byte[] bCrl : crlBytes) {
                if (bCrl != null) {
                    haveCrl = true;
                    break;
                }
            }
        }
        if (ocsp != null || haveCrl) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION));

            ASN1EncodableVector revocationV = new ASN1EncodableVector();

            if (haveCrl) {
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                for (byte[] bCrl : crlBytes) {
                    if (bCrl == null)
                        continue;
                    ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl));
                    v2.add(t.readObject());
                }
                revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            }

            if (ocsp != null) {
                DEROctetString doctet = new DEROctetString(ocsp);
                ASN1EncodableVector vo1 = new ASN1EncodableVector();
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
                v2.add(doctet);
                ASN1Enumerated den = new ASN1Enumerated(0);
                ASN1EncodableVector v3 = new ASN1EncodableVector();
                v3.add(den);
                v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
                vo1.add(new DERSequence(v3));
                revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1)));
            }

            v.add(new DERSet(new DERSequence(revocationV)));
            attribute.add(new DERSequence(v));
        }
        if (sigtype == PdfSigner.CryptoStandard.CADES) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2));

            ASN1EncodableVector aaV2 = new ASN1EncodableVector();
            AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid),
                    null);
            aaV2.add(algoId);
            MessageDigest md = SignUtils.getMessageDigest(getHashAlgorithm(), interfaceDigest);
            byte[] dig = md.digest(signCert.getEncoded());
            aaV2.add(new DEROctetString(dig));

            v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
            attribute.add(new DERSequence(v));
        }

        if (signaturePolicyIdentifier != null) {
            attribute.add(new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId,
                    new DERSet(signaturePolicyIdentifier)));
        }

        return new DERSet(attribute);
    } catch (Exception e) {
        throw new PdfException(e);
    }
}

From source file:com.modemo.javase.signature.ValidationTimeStamp.java

License:Apache License

/**
 * Extend CMS Signer Information with the TimeStampToken into the unsigned Attributes.
 *
 * @param signer information about signer
 * @return information about SignerInformation
 * @throws IOException//from   w  w  w.  j  ava2s . c  o m
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = tsaClient.getTimeStampToken(signer.getSignature());
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));

    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);

    // There is no other way changing the unsigned attributes of the signer information.
    // result is never null, new SignerInformation always returned, 
    // see source code of replaceUnsignedAttributes
    return SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes));
}

From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java

License:Mozilla Public License

/**
  * Used to build a PKCS7 object given all its properties (digest, certs, crls, raw signature, adbePkcs7Sha1...).
  **///from  w w  w .ja  v a2 s.c  o  m

//FIXME : move to other class !!!
public PDFEnvelopedSignature(byte[] digest, Certificate[] certChain, CRL[] crlList,
        OCSPResponse[] ocspResponseEncoded, String dataHashAlgorithm, String provider, byte signature[],
        byte adbePkcs7Sha1Data[], String digestEncryptionAlgorithm, Date signingTime) {
    try {
        log.debug(Channel.TECH, "Building PDFEnvelopedSignature object");
        Hashtable<DERObjectIdentifier, Attribute> signedAttributesHashtable = new Hashtable<DERObjectIdentifier, Attribute>();

        List<OCSPResponse> ocspResponses = ocspResponseEncoded == null ? null
                : Arrays.asList(ocspResponseEncoded);
        List<CRL> crls = null;
        if (crlList != null) {
            crls = Arrays.asList(crlList);
        }

        AlgorithmID algorithmID = CryptoConstants.AlgorithmID.valueOfTag(dataHashAlgorithm);
        if (algorithmID == null || algorithmID.getType() != AlgorithmType.DIGEST)
            throw new NoSuchAlgorithmException("Unknown Hash Algorithm " + dataHashAlgorithm);

        Attribute messageDigestAttribute = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        signedAttributesHashtable.put(CMSAttributes.messageDigest, messageDigestAttribute);
        this.signCert = (X509Certificate) certChain[0];
        dataDigestAlgorithm = algorithmID.getOID();
        this.crls = crls;
        this.certs = Arrays.asList(certChain);
        this.ocspResponses = ocspResponses;
        keyAndParameterAlgorithm = digestEncryptionAlgorithm;
        this.adbePkcs7Sha1Data = adbePkcs7Sha1Data;
        cmsGenerator = (CMSSignedDataStreamGenerator) CMSForPAdESBasicGenerator.buildCMSSignedGenerator(
                new ContentSignerWithProvidedSignatureValue(signature,
                        AlgorithmID.valueOfTag(getSignatureAlgorithm()).getOID()),
                true, BouncyCastleProvider.PROVIDER_NAME, signedAttributesHashtable, signCert, certs,
                signingTime, dataDigestAlgorithm, crls, ocspResponses);
        bOut = new ByteArrayOutputStream();
        sigOut = cmsGenerator.open(bOut, adbePkcs7Sha1Data != null);
        if (adbePkcs7Sha1Data != null)
            sigOut.write(adbePkcs7Sha1Data);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}