Example usage for org.bouncycastle.asn1 DEROctetString DEROctetString

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

Introduction

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

Prototype

public DEROctetString(ASN1Encodable obj) throws IOException 

Source Link

Document

Constructor from the encoding of an ASN.1 object.

Usage

From source file:com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.java

License:Open Source License

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);/*w ww. ja  v  a2 s  .  co  m*/
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    ASN1Set set = null;
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();
}

From source file:com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.java

License:Open Source License

private KeyTransRecipientInfo computeRecipientInfo(X509Certificate x509certificate, byte[] abyte0)
        throws GeneralSecurityException, IOException {
    ASN1InputStream asn1inputstream = new ASN1InputStream(
            new ByteArrayInputStream(x509certificate.getTBSCertificate()));
    TBSCertificateStructure tbscertificatestructure = TBSCertificateStructure
            .getInstance(asn1inputstream.readObject());
    AlgorithmIdentifier algorithmidentifier = tbscertificatestructure.getSubjectPublicKeyInfo().getAlgorithm();
    IssuerAndSerialNumber issuerandserialnumber = new IssuerAndSerialNumber(tbscertificatestructure.getIssuer(),
            tbscertificatestructure.getSerialNumber().getValue());
    Cipher cipher = Cipher.getInstance(algorithmidentifier.getAlgorithm().getId());
    try {//from   w  ww. j a va  2 s  .com
        cipher.init(1, x509certificate);
    } catch (InvalidKeyException e) {
        cipher.init(1, x509certificate.getPublicKey());
    }
    DEROctetString deroctetstring = new DEROctetString(cipher.doFinal(abyte0));
    RecipientIdentifier recipId = new RecipientIdentifier(issuerandserialnumber);
    return new KeyTransRecipientInfo(recipId, algorithmidentifier, deroctetstring);
}

From source file:com.itextpdf.text.pdf.security.OcspClientBouncyCastle.java

License:Open Source License

/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert   certificate of the issues
 * @param serialNumber   serial number/*from www  .  j ava 2  s  .c  o  m*/
 * @return   an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws OCSPException, IOException, OperatorException, CertificateEncodingException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(
            new JcaDigestCalculatorProviderBuilder().build().get(CertificateID.HASH_SHA1),
            new JcaX509CertificateHolder(issuerCert), serialNumber);

    // basic request generation with nonce
    OCSPReqBuilder gen = new OCSPReqBuilder();

    gen.addRequest(id);

    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false,
            new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded()));
    gen.setRequestExtensions(new Extensions(new Extension[] { ext }));

    return gen.build();
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source 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.//from  w  ww  .j a va  2s.  c om
 * @param secondDigest the digest in the authenticatedAttributes
 * @param signingTime the signing time in the authenticatedAttributes
 * @param tsaClient TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 * @since   2.1.6
 */
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, TSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, CryptoStandard sigtype) {
    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 (Object element : digestalgos) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new ASN1ObjectIdentifier((String) element));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.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 (Object element : certs) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) element).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

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

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

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

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestAlgorithmOid));
        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, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        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 (tsaClient != null) {
            byte[] tsImprint = tsaClient.getMessageDigest().digest(digest);
            byte[] tsToken = tsaClient.getTimeStampToken(tsImprint);
            if (tsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken);
                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 ASN1Integer(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // 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 ASN1ObjectIdentifier(SecurityIDs.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:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
 * /*from  ww  w.ja  v  a2  s .  c om*/
 * @param secondDigest the content digest
 * @param signingTime the signing time
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 */
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp,
        Collection<byte[]> crlBytes, 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_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        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 == 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 = interfaceDigest.getMessageDigest(getHashAlgorithm());
            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));
        }

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

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...).
  **//* w w w . ja  v a 2 s .  co 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);
    }
}

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

License:Mozilla Public License

/**
 * Gets the bytes for the PKCS#1 object.
 * @return a byte array/*w  ww .  java 2s. com*/
 */
public byte[] getEncodedPKCS1() {
    try {
        //            if (externalDigest != null)
        //                digest = externalDigest;
        //            else
        pkcs1SigValue = sig.sign();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DEROctetString(pkcs1SigValue));
        dout.close();

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

From source file:com.spilowagie.text.pdf.OcspClientBouncyCastle.java

License:Mozilla Public License

/**
 * Generates an OCSP request using BouncyCastle.
 * @param issuerCert   certificate of the issues
 * @param serialNumber   serial number/*from   w w w  . java2 s  .  c  om*/
 * @return   an OCSP request
 * @throws OCSPException
 * @throws IOException
 */
private static OCSPReq generateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws OCSPException, IOException {
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);

    // basic request generation with nonce
    OCSPReqGenerator gen = new OCSPReqGenerator();

    gen.addRequest(id);

    // create details for nonce extension
    Vector oids = new Vector();
    Vector values = new Vector();

    oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    values.add(new X509Extension(false,
            new DEROctetString(new DEROctetString(PdfEncryption.createDocumentId()).getEncoded())));

    gen.setRequestExtensions(new X509Extensions(oids, values));

    return gen.generate();
}

From source file:com.tremolosecurity.proxy.auth.ssl.OCSP.java

License:Apache License

private OCSPReq generateOcspRequest(X509Certificate issuerCert, BigInteger serialNumber)
        throws OCSPException, CertificateEncodingException, OperatorCreationException, IOException {

    BcDigestCalculatorProvider util = new BcDigestCalculatorProvider();

    // Generate the id for the certificate we are looking for
    CertificateID id = new CertificateID(util.get(CertificateID.HASH_SHA1),
            new X509CertificateHolder(issuerCert.getEncoded()), serialNumber);
    OCSPReqBuilder ocspGen = new OCSPReqBuilder();

    ocspGen.addRequest(id);//from   w  ww  .  j av  a  2 s  . c  om

    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Extension ext = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, true,
            new DEROctetString(nonce.toByteArray()));
    ocspGen.setRequestExtensions(new Extensions(new Extension[] { ext }));

    return ocspGen.build();
}

From source file:com.viettel.hqmc.DAO.FilesDAO.java

private static OCSPReq generateOCSPRequest2(X509Certificate issuerCert, BigInteger serialNumber)
        throws Exception {

    //TODO: Have to check if this is OK with synapse implementation.
    //Add provider BC
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CertificateID id = new CertificateID(CertificateID.HASH_SHA1, issuerCert, serialNumber);
    OCSPReqGenerator generator = new OCSPReqGenerator();
    generator.addRequest(id);/* w  w  w  .j  a v a2 s. c o  m*/
    BigInteger nonce = BigInteger.valueOf(System.currentTimeMillis());
    Vector<ASN1ObjectIdentifier> objectIdentifiers = new Vector<ASN1ObjectIdentifier>();
    Vector<X509Extension> values = new Vector<X509Extension>();
    objectIdentifiers.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce);
    values.add(new X509Extension(false, new DEROctetString(nonce.toByteArray())));
    generator.setRequestExtensions(new X509Extensions(objectIdentifiers, values));
    return generator.generate();
}