Example usage for org.bouncycastle.asn1 DEROutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:ElGamalPrivatePGKey.java

License:Open Source License

/**
 * Return a PKCS8 representation of the key. The sequence returned
 * represents a full PrivateKeyInfo object.
 *
 * @return a PKCS8 representation of the key.
 *//*from ww  w.j  av a2 s  .  com*/
public byte[] getEncoded() {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    PrivateKeyInfo info = new PrivateKeyInfo(new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm,
            new ElGamalParameter(elSpec.getP(), elSpec.getG()).getDERObject()), new DERInteger(getX()));

    try {
        dOut.writeObject(info);
        dOut.close();
    } catch (IOException e) {
        throw new RuntimeException("Error encoding ElGamal private key");
    }

    return bOut.toByteArray();
}

From source file:ElGamalPublicPGKey.java

License:Open Source License

public byte[] getEncoded() {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
            new AlgorithmIdentifier(OIWObjectIdentifiers.elGamalAlgorithm,
                    new ElGamalParameter(elSpec.getP(), elSpec.getG()).getDERObject()),
            new DERInteger(y));

    try {//ww  w.j a  v a 2  s .  com
        dOut.writeObject(info);
        dOut.close();
    } catch (IOException e) {
        throw new RuntimeException("Error encoding ElGamal public key");
    }

    return bOut.toByteArray();

}

From source file:com.aaasec.sigserv.csspsupport.pdfbox.PdfBoxSigUtil.java

License:EUPL

/**
 * A method that updates the PDF PKCS7 object from the model object with a signature,
 * certificates and SignedAttributes obtains from an external source. The model contains
 * //from  ww w . java2 s.c  om
 * <p>
 * The PKCS7 Signed data found in the model can be created using a different
 * private key and certificate chain. This method effectively replace the signature
 * value and certificate with the replacement data obtained from the model.
 * 
 * @param model A model for this signature replacement operation containing
 * necessary data for the process.
 * @return The bytes of an updated ODF signature PKCS7.
 */
public static byte[] updatePdfPKCS7(PdfSignModel model) {

    //New variables
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DEROutputStream dout = new DEROutputStream(bout);
    ASN1EncodableVector npkcs7 = new ASN1EncodableVector();
    ASN1EncodableVector nsd = new ASN1EncodableVector();
    ASN1EncodableVector nsi = new ASN1EncodableVector();

    try {
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(model.getSignedData().getEncoded()));

        //
        // Basic checks to make sure it's a PKCS#7 SignedData Object
        //
        ASN1Primitive pkcs7;

        try {
            pkcs7 = din.readObject();
        } catch (IOException e) {
            throw new IllegalArgumentException("Illegal PKCS7");
        }
        if (!(pkcs7 instanceof ASN1Sequence)) {
            throw new IllegalArgumentException("Illegal PKCS7");
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs7;
        ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(PdfObjectIds.ID_PKCS7_SIGNED_DATA)) {
            throw new IllegalArgumentException("No SignedData");
        }

        //Add Signed data content type to new PKCS7
        npkcs7.add(objId);

        /**
         * SignedData ::= SEQUENCE { version CMSVersion, digestAlgorithms
         * DigestAlgorithmIdentifiers, encapContentInfo
         * EncapsulatedContentInfo, certificates [0] IMPLICIT CertificateSet
         * OPTIONAL, crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
         * signerInfos SignerInfos }
         */
        //Get the SignedData sequence
        ASN1Sequence signedDataSeq = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject();
        int sdObjCount = 0;

        // the version
        nsd.add(signedDataSeq.getObjectAt(sdObjCount++));

        // the digestAlgorithms
        nsd.add(signedDataSeq.getObjectAt(sdObjCount++));

        // the possible ecapsulated content info
        nsd.add(signedDataSeq.getObjectAt(sdObjCount++));
        // the certificates. The certs are taken from the input parameters to the method            
        //ASN1EncodableVector newCerts = new ASN1EncodableVector();
        Certificate[] chain = model.getChain();
        ASN1Encodable[] newCerts = new ASN1Encodable[chain.length];
        //for (Certificate nCert : model.getCertChain()) {
        for (int i = 0; i < chain.length; i++) {
            ASN1InputStream cin = new ASN1InputStream(new ByteArrayInputStream(chain[i].getEncoded()));
            newCerts[i] = cin.readObject();

        }
        nsd.add(new DERTaggedObject(false, 0, new DERSet(newCerts)));

        //Step counter past tagged objects
        while (signedDataSeq.getObjectAt(sdObjCount) instanceof ASN1TaggedObject) {
            ++sdObjCount;
        }

        //SignerInfos is the next object in the sequence of Signed Data (first untagged after certs)
        ASN1Set signerInfos = (ASN1Set) signedDataSeq.getObjectAt(sdObjCount);
        if (signerInfos.size() != 1) {
            throw new IllegalArgumentException("Unsupported multiple signer infos");
        }
        ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0);
        int siCounter = 0;

        // SignerInfo sequence
        //
        // 0 - CMSVersion 
        // 1 - SignerIdentifier (CHOICE IssuerAndSerialNumber SEQUENCE) 
        // 2 - DigestAglorithmIdentifier
        // 3 - [0] IMPLICIT SignedAttributes SET 
        // 3 - Signature AlgorithmIdentifier 
        // 4 - Signature Value OCTET STRING 
        // 5 - [1] IMPLICIT UnsignedAttributes
        //
        //version
        nsi.add(signerInfo.getObjectAt(siCounter++));

        // signing certificate issuer and serial number
        Certificate sigCert = chain[0];
        ASN1EncodableVector issuerAndSerial = getIssuerAndSerial(sigCert);
        nsi.add(new DERSequence(issuerAndSerial));
        siCounter++;

        //Digest AlgorithmIdentifier
        nsi.add(signerInfo.getObjectAt(siCounter++));

        //Add signed attributes from signature service
        ASN1InputStream sigAttrIs = new ASN1InputStream(model.getCmsSigAttrBytes());
        nsi.add(new DERTaggedObject(false, 0, sigAttrIs.readObject()));

        //Step counter past tagged objects (because signedAttrs i optional in the input data)
        while (signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) {
            siCounter++;
        }

        //Signature Alg identifier
        nsi.add(signerInfo.getObjectAt(siCounter++));

        //Add new signature value from signing service
        nsi.add(new DEROctetString(model.getSignatureBytes()));
        siCounter++;

        //Add unsigned Attributes if present
        if (signerInfo.size() > siCounter && signerInfo.getObjectAt(siCounter) instanceof ASN1TaggedObject) {
            nsi.add(signerInfo.getObjectAt(siCounter));
        }

        /*
         * Final Assembly
         */
        // Add the SignerInfo sequence to the SignerInfos set and add this to the SignedData sequence
        nsd.add(new DERSet(new DERSequence(nsi)));
        // Add the SignedData sequence as a eplicitly tagged object to the pkcs7 object
        npkcs7.add(new DERTaggedObject(true, 0, new DERSequence(nsd)));

        dout.writeObject((new DERSequence(npkcs7)));
        byte[] pkcs7Bytes = bout.toByteArray();
        dout.close();
        bout.close();

        return pkcs7Bytes;

    } catch (Exception e) {
        throw new IllegalArgumentException(e.toString());
    }
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

License:Apache License

/**
 * Computes the digital signature of an array of data.
 *
 * @param data the data//from w  w  w .  j a v a2  s  . c  o  m
 * @return the digital signature
 * @throws IOException failed to read/write signature data
 * @throws CertificateEncodingException failed to sign the data
 * @throws OperatorCreationException failed to sign the data
 * @throws CMSException failed to sign the data
 */
private byte[] computePkcs7Signature(@NonNull byte[] data)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    CMSProcessableByteArray cmsData = new CMSProcessableByteArray(data);

    ArrayList<X509Certificate> certList = new ArrayList<>();
    certList.add(mCertificate);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    String signatureAlgName = mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm);
    ContentSigner shaSigner = new JcaContentSignerBuilder(signatureAlgName).build(mPrivateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(shaSigner, mCertificate));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(cmsData, false);

    ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();

    /*
     * DEROutputStream is not closeable! OMG!
     */
    DEROutputStream dos = null;
    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        dos = new DEROutputStream(outputBytes);
        dos.writeObject(asn1.readObject());

        DEROutputStream toClose = dos;
        dos = null;
        toClose.close();
    } catch (IOException e) {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException ee) {
                e.addSuppressed(ee);
            }
        }
    }

    return outputBytes.toByteArray();
}

From source file:com.android.builder.signing.SignedJarApkCreator.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);/*from w ww  .j a  v a 2  s .c  o  m*/
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(
            mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm)).build(mKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        DEROutputStream dos = new DEROutputStream(mOutputJar);
        try {
            dos.writeObject(asn1.readObject());
        } finally {
            dos.flush();
            dos.close();
        }
    }
}

From source file:com.android.builder.signing.SignedJarBuilder.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);//  www  .java2  s  . co  m
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm())
            .build(privateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}

From source file:com.mycompany.mavenproject1.Signer.java

private byte[] ConvertToDER(CMSSignedData cmsSignedData) throws IOException {

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream dOut = new DEROutputStream(bOut);
    dOut.writeObject(cmsSignedData.toASN1Structure().toASN1Primitive());
    dOut.close();
    return bOut.toByteArray();
}

From source file:com.orange.atk.sign.apk.SignedJarBuilder.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);/*from   w  w w  . java2s  .c o  m*/
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm())
            .build(privateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());
    dos.flush();
    dos.close();
    asn1.close();
}

From source file:es.unican.meteo.esgf.myproxyclient.MyProxyLogon.java

License:Open Source License

private static void printKey(PrivateKey paramPrivateKey, PrintStream paramPrintStream) throws IOException {
    paramPrintStream.println("-----BEGIN RSA PRIVATE KEY-----");
    ByteArrayInputStream localByteArrayInputStream = new ByteArrayInputStream(paramPrivateKey.getEncoded());
    ASN1InputStream localASN1InputStream = new ASN1InputStream(localByteArrayInputStream);
    DERObject localDERObject1 = localASN1InputStream.readObject();
    PrivateKeyInfo localPrivateKeyInfo = new PrivateKeyInfo((ASN1Sequence) localDERObject1);
    DERObject localDERObject2 = localPrivateKeyInfo.getPrivateKey();
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    DEROutputStream localDEROutputStream = new DEROutputStream(localByteArrayOutputStream);
    localDEROutputStream.writeObject(localDERObject2);
    printB64(localByteArrayOutputStream.toByteArray(), paramPrintStream);
    paramPrintStream.println("-----END RSA PRIVATE KEY-----");
    localASN1InputStream.close();
    localDEROutputStream.close();
}

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

License:Open Source License

@Override
public byte[] getBytes() throws DSSException {

    try {/*from  ww  w. ja v a2s  .c  o  m*/

        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        final DEROutputStream derOutputStream = new DEROutputStream(output);
        final byte[] encoded = signedData.getEncoded();
        final ASN1Primitive asn1Primitive = DSSASN1Utils.toASN1Primitive(encoded);
        derOutputStream.writeObject(asn1Primitive);
        derOutputStream.close();
        return output.toByteArray();
    } catch (IOException e) {

        throw new DSSException(e);
    }
}