Example usage for org.bouncycastle.asn1 ASN1OutputStream ASN1OutputStream

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

Introduction

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

Prototype

public ASN1OutputStream(OutputStream os) 

Source Link

Usage

From source file:VerifyDescriptors.java

License:Open Source License

private static void verifyConsensuses() throws Exception {
    File certsDirectory = new File("in/certs");
    File consensusDirectory = new File("in/consensuses");
    if (!certsDirectory.exists() || !consensusDirectory.exists()) {
        return;//  w  w w  .java 2s  . c om
    }
    Map<String, String> signingKeys = new HashMap<String, String>();

    DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader();
    certsReader.addDirectory(certsDirectory);
    Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors();
    int processedCerts = 0, verifiedCerts = 0;
    while (descriptorFiles.hasNext()) {
        DescriptorFile descriptorFile = descriptorFiles.next();
        if (descriptorFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": "
                    + descriptorFile.getException().getMessage());
            continue;
        }
        if (descriptorFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : descriptorFile.getDescriptors()) {
            if (!(descriptor instanceof DirectoryKeyCertificate)) {
                continue;
            }
            DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor;
            boolean isVerified = true;

            /* Verify that the contained fingerprint is a hash of the signing
             * key. */
            String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey());
            String fingerprintString = cert.getFingerprint().toLowerCase();
            if (!dirIdentityKeyHashString.equals(fingerprintString)) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the calculated directory identity key hash " + dirIdentityKeyHashString
                        + " does not match the contained fingerprint " + fingerprintString + "!");
                isVerified = false;
            }

            /* Verify that the router signature was created using the signing
             * key. */
            if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(),
                    cert.getDirIdentityKey())) {
                System.out.println("In " + descriptorFile.getFile()
                        + ", the decrypted directory key certification does not "
                        + "match the certificate digest!");
                isVerified = false;
            }

            /* Determine the signing key digest and remember the signing key
             * to verify consensus signatures. */
            String dirSigningKeyString = cert.getDirSigningKey();
            PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString));
            RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject();
            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
            new ASN1OutputStream(baos2)
                    .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(),
                            dirSigningKey.getPublicExponent()).toASN1Primitive());
            byte[] pkcs2 = baos2.toByteArray();
            byte[] dirSigningKeyHashBytes = new byte[20];
            SHA1Digest sha1_2 = new SHA1Digest();
            sha1_2.update(pkcs2, 0, pkcs2.length);
            sha1_2.doFinal(dirSigningKeyHashBytes, 0);
            String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase();
            signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey());

            processedCerts++;
            if (isVerified) {
                verifiedCerts++;
            }
        }
    }
    System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs.");

    DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader();
    consensusReader.addDirectory(consensusDirectory);
    Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors();
    int processedConsensuses = 0, verifiedConsensuses = 0;
    while (consensusFiles.hasNext()) {
        DescriptorFile consensusFile = consensusFiles.next();
        if (consensusFile.getException() != null) {
            System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": "
                    + consensusFile.getException().getMessage());
            continue;
        }
        if (consensusFile.getDescriptors() == null) {
            continue;
        }
        for (Descriptor descriptor : consensusFile.getDescriptors()) {
            if (!(descriptor instanceof RelayNetworkStatusConsensus)) {
                continue;
            }
            RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor;
            boolean isVerified = true;

            /* Verify all signatures using the corresponding certificates. */
            if (consensus.getDirectorySignatures().isEmpty()) {
                System.out.println(consensusFile.getFile() + " does not contain any signatures.");
                continue;
            }
            for (DirectorySignature signature : consensus.getDirectorySignatures().values()) {
                String signingKeyDigest = signature.getSigningKeyDigest();
                if (!signingKeys.containsKey(signingKeyDigest)) {
                    System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!");
                }
                if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(),
                        signingKeys.get(signingKeyDigest))) {
                    System.out.println("In " + consensusFile.getFile()
                            + ", the decrypted signature digest does not match the " + "consensus digest!");
                    isVerified = false;
                }
            }
            processedConsensuses++;
            if (isVerified) {
                verifiedConsensuses++;
            }
        }
    }
    System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses.");
}

From source file:VerifyDescriptors.java

License:Open Source License

private static String determineKeyHash(String key) throws Exception {
    PEMReader pemReader = new PEMReader(new StringReader(key));
    RSAPublicKey dirIdentityKey = (RSAPublicKey) pemReader.readObject();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new ASN1OutputStream(baos)
            .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirIdentityKey.getModulus(),
                    dirIdentityKey.getPublicExponent()).toASN1Primitive());
    byte[] pkcs = baos.toByteArray();
    byte[] dirIdentityKeyHashBytes = new byte[20];
    SHA1Digest sha1 = new SHA1Digest();
    sha1.update(pkcs, 0, pkcs.length);/*  ww w. j  ava2 s  . co  m*/
    sha1.doFinal(dirIdentityKeyHashBytes, 0);
    String keyHash = Hex.encodeHexString(dirIdentityKeyHashBytes);
    return keyHash;
}

From source file:bft.BFTNode.java

private byte[] encodeBlockHeaderASN1(Common.BlockHeader header) throws IOException {

    //convert long to byte array
    //ByteArrayOutputStream bos = new ByteArrayOutputStream();
    //ObjectOutput out = new ObjectOutputStream(bos);
    //out.writeLong(header.getNumber());
    //out.flush();
    //bos.flush();
    //out.close();
    //bos.close();
    //byte[] number = bos.toByteArray();
    // encode the header in ASN1 format
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ASN1OutputStream asnos = new ASN1OutputStream(bos);

    asnos.writeObject(new ASN1Integer((int) header.getNumber()));
    //asnos.writeObject(new DERInteger((int) header.getNumber()));
    asnos.writeObject(new DEROctetString(header.getPreviousHash().toByteArray()));
    asnos.writeObject(new DEROctetString(header.getDataHash().toByteArray()));
    asnos.flush();/*from w  w w  .ja  v  a2s  . c o  m*/
    bos.flush();
    asnos.close();
    bos.close();

    byte[] buffer = bos.toByteArray();

    //Add golang idiosyncrasies
    byte[] bytes = new byte[buffer.length + 2];
    bytes[0] = 48; // no idea what this means, but golang's encoding uses it
    bytes[1] = (byte) buffer.length; // length of the rest of the octet string, also used by golang
    for (int i = 0; i < buffer.length; i++) { // concatenate
        bytes[i + 2] = buffer[i];
    }

    return bytes;
}

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

License:Open Source License

private byte[] genOutput(DERSequence whole) throws IOException {
    final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    final ASN1OutputStream dout = new ASN1OutputStream(bOut);
    dout.writeObject(whole);//from   w  w w  .  java 2s .c o  m
    dout.close();

    return bOut.toByteArray();
}

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

License:Open Source License

public static byte[] convSiToByte(ASN1Set newSi) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ASN1OutputStream aOut = new ASN1OutputStream(bOut);

    aOut.writeObject(newSi);/*from   w  ww .  j  ava  2s . co  m*/

    aOut.close();

    byte[] saAsBytes = bOut.toByteArray();
    return saAsBytes;
}

From source file:cc.arduino.plugins.unowifi.certs.WiFi101Certificate.java

License:Open Source License

private static byte[] encodeTimestamp(Date notBefore) throws IOException {
    ByteArrayOutputStream encoded = new ByteArrayOutputStream();
    ASN1OutputStream asn1 = new ASN1OutputStream(encoded);
    asn1.writeObject(new Time(notBefore));
    return Arrays.copyOfRange(encoded.toByteArray(), 2, 22);
}

From source file:cc.arduino.plugins.wifi101.certs.WiFi101Certificate.java

License:Open Source License

private static byte[] encodeTimestampV0(Date notBefore) throws IOException {
    ByteArrayOutputStream encoded = new ByteArrayOutputStream();
    ASN1OutputStream asn1 = new ASN1OutputStream(encoded);
    asn1.writeObject(new Time(notBefore));
    return Arrays.copyOfRange(encoded.toByteArray(), 2, 22);
}

From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * converts a RSAPublicKey into PKCS1-encoding (ASN.1).
 *
 * @param pubKeyStruct//w  w  w .ja v a 2s  .c  o m
 * @return PKCS1-encoded RSA PUBLIC KEY
 * @see JCERSAPublicKey
 */
public static byte[] getPKCS1EncodingFromRSAPublicKey(final RSAPublicKey pubKeyStruct) {
    try {
        final RSAPublicKeyStructure myKey = new RSAPublicKeyStructure(pubKeyStruct.getModulus(),
                pubKeyStruct.getPublicExponent());
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        final ASN1OutputStream aOut = new ASN1OutputStream(bOut);
        aOut.writeObject(myKey.toASN1Object());
        aOut.close();
        return bOut.toByteArray();
    } catch (final Exception e) {
        return null;
    }
}

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

License:Open Source License

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

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

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

From source file:com.itextpdf.signatures.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  ww w  . j a va 2  s.c  o m
 *
 * @param secondDigest the digest in the authenticatedAttributes
 * @param tsaClient    TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 */
public byte[] getEncodedPKCS7(byte[] secondDigest, ITSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, PdfSigner.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(DERNull.INSTANCE);
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        if (secondDigest != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, ocsp, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        v.add(DERNull.INSTANCE);
        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 PdfException(e);
    }
}