Example usage for org.bouncycastle.asn1 ASN1OutputStream close

List of usage examples for org.bouncycastle.asn1 ASN1OutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

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.//w w w . j  a  va2 s .  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.opentrust.spi.pdf.PDFEnvelopedSignature.java

License:Mozilla Public License

/**
 * Gets the bytes for the PKCS#1 object.
 * @return a byte array//from   www .ja v  a2s . c om
 */
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: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                                                                       
 *//* ww  w  .  j  a v a2 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:org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi.java

License:Open Source License

/**
 * Store the key from _id into a keystore file
 *///from w  w w  .j ava 2  s  .c o m
@Override
public void engineStore(OutputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    if (null == _id)
        throw new IOException("Key not entered yet");
    ASN1OutputStream aos = new ASN1OutputStream(stream);
    Tuple<SecretKeySpec, SecretKeySpec> keys = initializeForAES(password);
    try {
        byte[] iv = new byte[IV_SIZE];
        _random.nextBytes(iv);
        byte[] aesCBC = null;
        Cipher cipher = Cipher.getInstance(AES_CRYPTO_ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, keys.first(), ivspec);
        aesCBC = cipher.doFinal(_id);
        _macKeyMac.init(keys.second());
        byte[] checkbuf = new byte[iv.length + aesCBC.length];
        System.arraycopy(iv, 0, checkbuf, 0, iv.length);
        System.arraycopy(aesCBC, 0, checkbuf, iv.length, aesCBC.length);
        byte[] part3 = _macKeyMac.doFinal(checkbuf);
        // TODO might be a better way to do this but am not sure how
        // (and its not really that important anyway)
        byte[] asn1buf = new byte[iv.length + aesCBC.length + part3.length];
        System.arraycopy(checkbuf, 0, asn1buf, 0, checkbuf.length);
        System.arraycopy(part3, 0, asn1buf, iv.length + aesCBC.length, part3.length);
        ASN1OctetString os = new DEROctetString(asn1buf);
        ASN1Encodable[] ae = new ASN1Encodable[3];
        ae[0] = _version;
        ae[1] = _oid;
        ae[2] = os;
        DERSequence ds = new DERSequence(ae);
        aos.writeObject(ds);
        aos.flush();
        aos.close();
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.jclouds.crypto.Pems.java

License:Apache License

static byte[] getEncoded(RSAPrivateCrtKey key) {
    RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(key.getModulus(), key.getPublicExponent(),
            key.getPrivateExponent(), key.getPrimeP(), key.getPrimeQ(), key.getPrimeExponentP(),
            key.getPrimeExponentQ(), key.getCrtCoefficient());

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    try {//from ww w  .j  a v a2 s  . c o  m
        aOut.writeObject(keyStruct);
        aOut.close();
    } catch (IOException e) {
        Throwables.propagate(e);
    }

    return bOut.toByteArray();
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

@Override
public void writeRSAPrivateKey(Writer _out, RSAPrivateCrtKey obj, String algo, char[] f) throws IOException {
    assert (obj != null);
    BufferedWriter out = makeBuffered(_out);
    RSAPrivateKeyStructure keyStruct = new RSAPrivateKeyStructure(obj.getModulus(), obj.getPublicExponent(),
            obj.getPrivateExponent(), obj.getPrimeP(), obj.getPrimeQ(), obj.getPrimeExponentP(),
            obj.getPrimeExponentQ(), obj.getCrtCoefficient());

    // convert to bytearray
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    aOut.writeObject(keyStruct);//from   ww w .  j a  v a  2s  . co  m
    aOut.close();

    byte[] encoding = bOut.toByteArray();

    if (algo != null && f != null) {
        byte[] salt = new byte[8];
        byte[] encData = null;
        random.nextBytes(salt);
        OpenSSLPBEParametersGenerator pGen = new OpenSSLPBEParametersGenerator();
        pGen.init(PBEParametersGenerator.PKCS5PasswordToBytes(f), salt);
        SecretKey secretKey = null;

        if (algo.startsWith("DES")) {
            // generate key
            int keyLength = 24;
            if (algo.equalsIgnoreCase("DESEDE")) {
                algo = "DESede/CBC/PKCS5Padding";
            }
            KeyParameter param = (KeyParameter) pGen.generateDerivedParameters(keyLength * 8);
            secretKey = new SecretKeySpec(param.getKey(), algo.split("/")[0]);
        } else {
            throw new IOException("unknown algorithm `" + algo + "' in write_DSAPrivateKey");
        }

        // cipher  
        try {
            Cipher c = Cipher.getInstance(algo);
            c.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(salt));
            encData = c.doFinal(encoding);
        } catch (Exception e) {
            throw new IOException("exception using cipher: " + e.toString());
        }

        // write the data
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        out.write("Proc-Type: 4,ENCRYPTED");
        out.newLine();
        out.write("DEK-Info: DES-EDE3-CBC,");
        writeHexEncoded(out, salt);
        out.newLine();
        out.newLine();
        writeEncoded(out, encData);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.flush();
    } else {
        out.write(BEF_G + PEM_STRING_RSA + AFT);
        out.newLine();
        writeEncoded(out, encoding);
        out.write(BEF_E + PEM_STRING_RSA + AFT);
        out.newLine();
        out.flush();
    }
}

From source file:org.opensc.pkcs15.application.impl.ApplicationFactoryImpl.java

License:Apache License

/**
 * Write the applications directory to the token.
 * //from  w  w w .j a  v a2s .  c  o  m
 * @param token The token to write to.
 * @param apps The list of application templates to write.
 * @throws IOException Upon errors.
 */
protected void writeApplications(Token token, ISO7816Applications apps) throws IOException {
    token.selectMF();

    EF ef = null;

    try {
        ef = token.selectEF(DIR_PATH);
    } catch (PKCS15Exception e) {
        if (e.getErrorCode() != PKCS15Exception.ERROR_FILE_NOT_FOUND)
            throw e;
    }

    if (ef == null) {
        token.createEF(DIR_PATH, 512L,
                new EFAclImpl(TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS,
                        TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS,
                        TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS, TokenFileAcl.AC_ALWAYS));

        ef = token.selectEF(DIR_PATH);
    }

    OutputStream os = token.writeEFData();

    ASN1OutputStream aos = new ASN1OutputStream(os);

    if (apps.getApplications() != null)
        for (ISO7816ApplicationTemplate template : apps.getApplications())
            aos.writeObject(template.toASN1Object());

    aos.write(0);
    aos.write(0);
    aos.close();

}

From source file:org.opensc.pkcs15.asn1.PKCS15Objects.java

License:Apache License

/**
 * Write this instance to an OuputStream. The stream is closed after
 * writing all members.//w  ww. j  ava  2 s .  c o m
 * 
 * @param os The stream to write to.
 * @throws IOException Upon write errors.
 */
public void writeInstance(OutputStream os) throws IOException {

    ASN1OutputStream aos = new ASN1OutputStream(os);

    // write authentication objects first, in order to be compliant
    // with opensc tokens.
    // (This eases the conception of Unit Tests against opensc
    if (this.authObjects != null)
        aos.writeObject(new DERTaggedObject(8, this.authObjects));

    if (this.privateKeys != null)
        aos.writeObject(new DERTaggedObject(0, this.privateKeys));

    if (this.publicKeys != null)
        aos.writeObject(new DERTaggedObject(1, this.publicKeys));

    if (this.trustedPublicKeys != null)
        aos.writeObject(new DERTaggedObject(2, this.trustedPublicKeys));

    // secret keys to come...

    if (this.certificates != null)
        aos.writeObject(new DERTaggedObject(4, this.certificates));

    if (this.trustedCertificates != null)
        aos.writeObject(new DERTaggedObject(5, this.trustedCertificates));

    if (this.usefulCertificates != null)
        aos.writeObject(new DERTaggedObject(6, this.usefulCertificates));

    // data objects to come...

    // write END_OF_STREAM
    aos.write(0);
    aos.write(0);
    aos.close();
}

From source file:org.opensc.pkcs15.asn1.proxy.StreamResolverDirectory.java

License:Apache License

@Override
public void updateEntity(ReferenceType ref, EntityType entity) {

    try {// w w  w.  j  av  a 2  s  .  com
        ASN1OutputStream aos = new ASN1OutputStream(this.streamResolver.writeReference(ref));

        aos.writeObject(entity);
        aos.close();

    } catch (IOException e) {
        throw new IllegalArgumentException("Reference [" + ref + "] cannot be written.", e);
    }
}

From source file:org.opensc.pkcs15.asn1.sequence.SequenceOfFactory.java

License:Apache License

/**
 * Write all elements of the supplied SequenceOf to the given OutputStream. 
 * //from   w ww. j  a va  2  s  . com
 * @param os The OutputStream to write to. The stream is closed by this
 *           function after writing all members of <code>seq</code>.
 * @param seq The sequence to write.
 * @throws IOException
 */
public void writeInstance(OutputStream os, SequenceOf<EntityType> seq) throws IOException {

    ASN1OutputStream aos = new ASN1OutputStream(os);

    List<EntityType> sequence = seq.getSequence();

    if (sequence != null) {

        for (EntityType e : sequence) {

            aos.writeObject(e);
        }
    }

    // write END_OF_STREAM
    aos.write(0);
    aos.write(0);
    aos.close();
}