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:es.gob.afirma.signers.pades.ltv.PdfDocumentSecurityStore.java

License:Open Source License

synchronized int registerOcspBasicResp(final byte basicResp[]) throws IOException {
    final ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    v2.add(new DEROctetString(basicResp));
    final ASN1EncodableVector v3 = new ASN1EncodableVector();
    v3.add(new ASN1Enumerated(0));
    v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
    return registerOcspResp(new DERSequence(v3).getEncoded());
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client                  
 * may be provided.                                                                     
 * @param secondDigest the digest in the authenticatedAttributes                        
 * @param signingTime the signing time in the authenticatedAttributes                   
 * @param tsaUrl TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object                              
 * @since   2.1.6                                                                       
 *//* w  ww  .  java2  s  . c o m*/
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, String tsaUrl, byte[] ocsp) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }

        // Create the set of Hash algorithms                                                                
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Iterator it = digestalgos.iterator(); it.hasNext();) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new DERObjectIdentifier((String) it.next()));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.                                                                          
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);

        // Get all the certificates                                                                         
        //                                                                                                  
        v = new ASN1EncodableVector();
        for (Iterator i = certs.iterator(); i.hasNext();) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) i.next()).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.                                                                                    
        //                                                                                                                 
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version                                                                                      
        //                                                                                                                 
        signerinfo.add(new DERInteger(signerversion));

        v = new ASN1EncodableVector();
        v.add(getIssuer(signCert.getTBSCertificate()));
        v.add(new DERInteger(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm                                                                                         
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(digestAlgorithm));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present                                                                      
        if (secondDigest != null && signingTime != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp)));
        }
        // Add the digestEncryptionAlgorithm                                                                               
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(digestEncryptionAlgorithm));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the digest                                                                                                  
        signerinfo.add(new DEROctetString(digest));

        // When requested, go get and add the timestamp. May throw an exception.                                           
        // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15                                             
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest                                             
        if (tsaUrl != null) {
            byte[] tsImprint = MessageDigest.getInstance("SHA-1").digest(digest);

            TSResponse response = TimeStampFactory.getTimeStampResponse(tsaUrl, tsImprint, false);
            byte[] tsToken = response.getEncodedToken();

            //Strip the status code out of the response, the adobe validator requieres it. 
            //TODO: Research about this.
            byte[] status = { 0x30, (byte) 0x82, 0x03, (byte) 0xA7, 0x30, 0x03, 0x02, 0x01, 0x00 };
            byte[] modTsToken = new byte[tsToken.length - status.length];
            System.arraycopy(tsToken, status.length, modTsToken, 0, tsToken.length - status.length);

            if (modTsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(modTsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }

        // Finally build the body out of all the components above                                                          
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        if (!crls.isEmpty()) {
            v = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext();) {
                ASN1InputStream t = new ASN1InputStream(
                        new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
                v.add(t.readObject());
            }
            DERSet dercrls = new DERSet(v);
            body.add(new DERTaggedObject(false, 1, dercrls));
        }

        // Only allow one signerInfo                                                                                       
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell                                                         
        // and return it                                                                                                   
        //                                                                                                                 
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier(ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp) {
    try {// w ww .ja v  a  2s .  c  o  m
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_CONTENT_TYPE));
        v.add(new DERSet(new DERObjectIdentifier(ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier(ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        if (ocsp != null) {
            v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION));
            DEROctetString doctet = new DEROctetString(ocsp);
            ASN1EncodableVector vo1 = new ASN1EncodableVector();
            ASN1EncodableVector v2 = new ASN1EncodableVector();
            v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
            v2.add(doctet);
            DEREnumerated den = new DEREnumerated(0);
            ASN1EncodableVector v3 = new ASN1EncodableVector();
            v3.add(den);
            v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            vo1.add(new DERSequence(v3));
            v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 1, new DERSequence(vo1)))));
            attribute.add(new DERSequence(v));
        } else if (!crls.isEmpty()) {
            v = new ASN1EncodableVector();
            v.add(new DERObjectIdentifier(ID_ADBE_REVOCATION));
            ASN1EncodableVector v2 = new ASN1EncodableVector();
            for (Iterator i = crls.iterator(); i.hasNext();) {
                ASN1InputStream t = new ASN1InputStream(
                        new ByteArrayInputStream(((X509CRL) i.next()).getEncoded()));
                v2.add(t.readObject());
            }
            v.add(new DERSet(new DERSequence(new DERTaggedObject(true, 0, new DERSequence(v2)))));
            attribute.add(new DERSequence(v));
        }
        return new DERSet(attribute);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Returns the NameConstraints structure of the restrictions.
 * /*from w w w .j  a  va  2 s .co m*/
 * @return The DERSequence containing the NameConstraints structure.
 */
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector nameConstraintsSequenceVector = new ASN1EncodableVector();

    addTaggedSequenceOfSubtrees(0, permittedGeneralSubtrees, nameConstraintsSequenceVector);
    addTaggedSequenceOfSubtrees(1, excludedGeneralSubtrees, nameConstraintsSequenceVector);

    return new DERSequence(nameConstraintsSequenceVector);
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyAddressRestrictionData.java

License:Open Source License

/**
 * Adds, with the given tag, a DER sequence object that contains the
 * GeneralSubtree objects into the ASN1Vector.
 * /*from ww w . j  av a  2  s .co m*/
 * @param tagNo
 *                The tag to tag the object.
 * @param subtrees
 *                The Vector of GeneralSubtree objects. Null will throw
 *                NullPointerException. An empty Vector will not be
 *                added.
 * @param asn1Vector
 *                The vector to add the subtrees sequence with the given
 *                tag.
 */
private static void addTaggedSequenceOfSubtrees(int tagNo, List<GeneralSubtree> subtrees,
        ASN1EncodableVector asn1Vector) {
    if (!subtrees.isEmpty()) {
        ASN1EncodableVector subtreesSequenceVector = new ASN1EncodableVector();

        Iterator<GeneralSubtree> generalSubtreesEnum = subtrees.iterator();
        while (generalSubtreesEnum.hasNext()) {
            subtreesSequenceVector.add(generalSubtreesEnum.next());
        }
        asn1Vector.add(new DERTaggedObject(tagNo, new DERSequence(subtreesSequenceVector)));
    }
}

From source file:eu.emi.security.authn.x509.helpers.proxy.X509v3CertificateBuilder.java

License:Open Source License

private X509Certificate sign(TBSCertificate toSign, AlgorithmIdentifier sigAlg, String sigAlgName,
        PrivateKey key, String provider, SecureRandom random)
        throws InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException,
        IOException, CertificateParsingException

{
    byte[] signature = calculateSignature(sigAlgName, provider, key, random, toSign);

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(toSign);/*w ww.java2 s . com*/
    v.add(sigAlg.toASN1Primitive());
    v.add(new DERBitString(signature));
    DERSequence derCertificate = new DERSequence(v);
    CertificateFactory factory;
    try {
        factory = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(derCertificate.getEncoded(ASN1Encoding.DER));
        return (X509Certificate) factory.generateCertificate(bais);
    } catch (CertificateException e) {
        throw new RuntimeException("The generated proxy " + "certificate was not parsed by the JDK", e);
    }
}

From source file:eu.emi.security.authn.x509.proxy.ProxyPolicy.java

License:Open Source License

/**
 * output the ASN1 object of the proxy policy.
 * /*w  ww .j a va 2 s .  c o m*/
 * @see org.bouncycastle.asn1.ASN1Object#toASN1Object()
 */
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(oid));
    if (policy != null)
        v.add(DEROctetString.getInstance(policy));

    return new DERSequence(v);
}

From source file:eu.europa.ec.markt.dss.mocca.MOCCASignatureTokenConnection.java

License:Open Source License

/**
 * The ECDSA_SIG structure consists of two BIGNUMs for the r and s value of a ECDSA signature (see X9.62 or FIPS
 * 186-2).<br>/*from  w  w w  . j  a va  2  s. com*/
 * This encoding is not implemented at the level of MOCCA!
 *
 * @param signedStream
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
private static byte[] encode(byte[] signedStream) throws DSSException {

    final int half = signedStream.length / 2;
    final byte[] firstPart = new byte[half];
    final byte[] secondPart = new byte[half];

    System.arraycopy(signedStream, 0, firstPart, 0, half);
    System.arraycopy(signedStream, half, secondPart, 0, half);

    final BigInteger r = new BigInteger(1, firstPart);
    final BigInteger s = new BigInteger(1, secondPart);

    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(new DERInteger(r));
    v.add(new DERInteger(s));

    return DSSASN1Utils.getDEREncoded(new DERSequence(v));
}

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)//from ww  w.  j a  v  a  2  s .  com
 * 5.11.2 signer-location Attribute
 * The signer-location attribute specifies a mnemonic for an address associated with the signer at a particular
 * geographical (e.g. city) location. The mnemonic is registered in the country in which the signer is located and is used in
 * the provision of the Public Telegram Service (according to Recommendation ITU-T F.1 [11]).
 * The signer-location attribute shall be a signed attribute.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addSignerLocation(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    if (!padesUsage) {
        /*
         * In PAdES, the role is in the signature dictionary
           */
        final BLevelParameters.SignerLocation signerLocationParameter = parameters.bLevel().getSignerLocation();
        if (signerLocationParameter != null) {

            final DERUTF8String country = signerLocationParameter.getCountry() == null ? null
                    : new DERUTF8String(signerLocationParameter.getCountry());
            final DERUTF8String locality = signerLocationParameter.getLocality() == null ? null
                    : new DERUTF8String(signerLocationParameter.getLocality());
            final ASN1EncodableVector postalAddress = new ASN1EncodableVector();
            final List<String> postalAddressParameter = signerLocationParameter.getPostalAddress();
            if (postalAddressParameter != null) {

                for (final String addressLine : postalAddressParameter) {

                    postalAddress.add(new DERUTF8String(addressLine));
                }
            }
            final DERSequence derSequencePostalAddress = new DERSequence(postalAddress);
            final SignerLocation signerLocation = new SignerLocation(country, locality,
                    derSequencePostalAddress);
            final DERSet attrValues = new DERSet(signerLocation);
            final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_ets_signerLocation,
                    attrValues);
            signedAttributes.add(attribute);
        }
    }
}

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)//  www .j  a  va2s.  c  o m
 * <p/>
 * 5.11.1 commitment-type-indication Attribute
 * There may be situations where a signer wants to explicitly indicate to a verifier that by signing the data, it illustrates a
 * type of commitment on behalf of the signer. The commitment-type-indication attribute conveys such
 * information.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addCommitmentType(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) {

    // TODO (19/08/2014): commitmentTypeQualifier is not implemented
    final BLevelParameters bLevelParameters = parameters.bLevel();

    final List<String> commitmentTypeIndications = bLevelParameters.getCommitmentTypeIndications();
    if (commitmentTypeIndications != null && !commitmentTypeIndications.isEmpty()) {

        final int size = commitmentTypeIndications.size();
        ASN1Encodable[] asn1Encodables = new ASN1Encodable[size];
        for (int ii = 0; ii < size; ii++) {

            final String commitmentTypeId = commitmentTypeIndications.get(ii);
            final ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(commitmentTypeId);
            // final CommitmentTypeIndication commitmentTypeIndication = new CommitmentTypeIndication(objectIdentifier);
            //            final ASN1Primitive asn1Primitive = commitmentTypeIndication.toASN1Primitive();
            asn1Encodables[ii] = new DERSequence(objectIdentifier);
        }
        final DERSet attrValues = new DERSet(asn1Encodables);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_ets_commitmentType, attrValues);
        signedAttributes.add(attribute);
    }
}