Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:com.android.signapk.SignApk.java

License:Apache License

/** Read a PKCS#8 format private key. */
private static PrivateKey readPrivateKey(File file) throws IOException, GeneralSecurityException {
    DataInputStream input = new DataInputStream(new FileInputStream(file));
    try {/*  w  w  w  . j av  a2  s. c o m*/
        byte[] bytes = new byte[(int) file.length()];
        input.read(bytes);

        /* Check to see if this is in an EncryptedPrivateKeyInfo structure. */
        PKCS8EncodedKeySpec spec = decryptPrivateKey(bytes, file);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        /*
         * Now it's in a PKCS#8 PrivateKeyInfo structure. Read its Algorithm
         * OID and use that to construct a KeyFactory.
         */
        ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()));
        PrivateKeyInfo pki = PrivateKeyInfo.getInstance(bIn.readObject());
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();

        return KeyFactory.getInstance(algOid).generatePrivate(spec);
    } finally {
        input.close();
    }
}

From source file:com.android.signapk.SignApk.java

License:Apache License

/** Sign data and write the digital signature to 'out'. */
private static void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey,
        OutputStream out)//from  w w  w. j a va2  s.  c  o  m
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>(1);
    certList.add(publicKey);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner signer = new JcaContentSignerBuilder(getSignatureAlgorithm(publicKey))
            .setProvider(sBouncyCastleProvider).build(privateKey);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(sBouncyCastleProvider).build())
                    .setDirectSignature(true).build(signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

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

From source file:com.awcoleman.BouncyCastleGenericCDRHadoop.RawFileRecordReader.java

License:Apache License

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    path = ((FileSplit) split).getPath();
    FileSystem fs = path.getFileSystem(conf);
    FSDataInputStream fsin = fs.open(path);
    is = decompressStream(fsin);/*  w  ww . j  a  va  2 s. c o m*/
    asnin = new ASN1InputStream(is);
}

From source file:com.awcoleman.BouncyCastleGenericCDRHadoop.StandaloneDecoder.java

License:Apache License

public StandaloneDecoder(String filename) throws IOException {

    File fileIn = new File(filename);
    FileInputStream fin = new FileInputStream(fileIn);
    InputStream is = decompressStream(fin);

    ASN1InputStream asnin = new ASN1InputStream(is);
    ASN1Primitive obj = null;/*from   w w  w  .  jav a 2  s  .  co  m*/

    while ((obj = asnin.readObject()) != null) {

        CallDetailRecord thisCdr = new CallDetailRecord((ASN1Sequence) obj);

        System.out.println("CallDetailRecord " + thisCdr.getRecordNumber() + " Calling "
                + thisCdr.getCallingNumber() + " Called " + thisCdr.getCalledNumber() + " Start Date-Time "
                + thisCdr.getStartDate() + "-" + thisCdr.getStartTime() + " duration " + thisCdr.getDuration());

    }

    asnin.close();
    is.close();
    fin.close();
}

From source file:com.awcoleman.BouncyCastleGenericCDRHadoopWithWritable.RawFileRecordReader.java

License:Apache License

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    path = ((FileSplit) split).getPath();
    FileSystem fs = path.getFileSystem(conf);
    FSDataInputStream fsin = fs.open(path);
    is = decompressStream(fsin);//  www .  j  ava 2 s  .  com
    asnin = new ASN1InputStream(is);

    recordCounter = 0;
}

From source file:com.bitsofproof.supernode.api.ECKeyPair.java

License:Apache License

public static boolean verify(byte[] hash, byte[] signature, byte[] pub) {
    ASN1InputStream asn1 = new ASN1InputStream(signature);
    try {//  ww w. j a va2 s.c o  m
        ECDSASigner signer = new ECDSASigner();
        signer.init(false, new ECPublicKeyParameters(curve.getCurve().decodePoint(pub), domain));

        DLSequence seq = (DLSequence) asn1.readObject();
        BigInteger r = ((DERInteger) seq.getObjectAt(0)).getPositiveValue();
        BigInteger s = ((DERInteger) seq.getObjectAt(1)).getPositiveValue();
        return signer.verifySignature(hash, r, s);
    } catch (Exception e) {
        // threat format errors as invalid signatures
        return false;
    } finally {
        try {
            asn1.close();
        } catch (IOException e) {
        }
    }
}

From source file:com.example.androidtest.SslUtil.java

License:Open Source License

/**
 * Creates an AuthorityKeyIdentifier from a public key, name, and serial
 * number./*from   w  ww  . j  a  v a 2 s.c  o  m*/
 * <p>
 * {@link AuthorityKeyIdentifierStructure} is <i>almost</i> perfect for this,
 * but sadly it does not have a constructor suitable for us:
 * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(PublicKey)}
 * does not set the serial number or name (which is important to us), while 
 * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(X509Certificate)}
 * sets those fields but needs a completed certificate to do so.
 * <p>
 * This method addresses the gap in available {@link AuthorityKeyIdentifier}
 * constructors provided by BouncyCastle; its implementation is derived from
 * {@link AuthorityKeyIdentifierStructure#AuthorityKeyIdentifierStructure(X509Certificate)}.
 *  
 * @param publicKey  the public key
 * @param name  the name
 * @param serialNumber  the serial number
 * @return  a new {@link AuthorityKeyIdentifier}
 */
private static AuthorityKeyIdentifier createAuthorityKeyIdentifier(PublicKey publicKey, X509Name name,
        BigInteger serialNumber) {
    GeneralName genName = new GeneralName(name);
    SubjectPublicKeyInfo info;
    try {
        info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(publicKey.getEncoded()).readObject());
    } catch (IOException e) {
        throw new RuntimeException("Error encoding public key");
    }
    return new AuthorityKeyIdentifier(info, new GeneralNames(genName), serialNumber);
}

From source file:com.github.horrorho.inflatabledonkey.data.der.DERUtils.java

License:Open Source License

public static <T> Optional<T> parse(byte[] data, Function<ASN1Primitive, T> function) {
    try (ASN1InputStream asN1InputStream = new ASN1InputStream(data)) {
        ASN1Primitive primitive = asN1InputStream.readObject();

        return parse(primitive, function);

    } catch (IOException ex) {
        logger.warn("-- parse() - IOException: {}", ex);
        return Optional.empty();
    }//from  w  w  w .  j  a  v a2s .c  om
}

From source file:com.goodvikings.cryptim.api.KeyRing.java

License:BEER-WARE LICENSE

private void ASN1DecodeKeys(byte[] plain) throws IOException, PGPException, NoSuchProviderException,
        ParseException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
    JcaPGPKeyConverter converter = new JcaPGPKeyConverter();

    ASN1Sequence seq = (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(plain)).readObject();

    PGPPublicKey pub = converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL,
            new RSAPublicKeyImpl(
                    ((ASN1OctetString) ((ASN1Sequence) seq.getObjectAt(0)).getObjectAt(1)).getOctets()),
            ((ASN1UTCTime) ((ASN1Sequence) seq.getObjectAt(0)).getObjectAt(0)).getAdjustedDate());
    kp = new PGPKeyPair(pub, converter.getPGPPrivateKey(pub, KeyFactory.getInstance("RSA")
            .generatePrivate(new PKCS8EncodedKeySpec(((ASN1OctetString) seq.getObjectAt(1)).getOctets()))));

    ASN1Sequence keySeq = (ASN1Sequence) seq.getObjectAt(2);

    for (int i = 0; i < keySeq.size(); i++) {
        keys.put(((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(0)).getString(),
                converter.getPGPPublicKey(PGPPublicKey.RSA_GENERAL, new RSAPublicKeyImpl(
                        ((ASN1OctetString) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(3)).getOctets()),
                        ((ASN1UTCTime) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(2))
                                .getAdjustedDate()));
        nicks.put(((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(0)).getString(),
                ((DERUTF8String) ((ASN1Sequence) keySeq.getObjectAt(i)).getObjectAt(1)).getString());
    }/*  w ww  .j  av  a  2s  . co  m*/
}

From source file:com.google.bitcoin.core.ECKey.java

License:Apache License

private static BigInteger extractPrivateKeyFromASN1(byte[] asn1privkey) {
    // To understand this code, see the definition of the ASN.1 format for EC private keys in the OpenSSL source
    // code in ec_asn1.c:
    ///*from   w ww.j  av a  2s  .c o m*/
    // ASN1_SEQUENCE(EC_PRIVATEKEY) = {
    //   ASN1_SIMPLE(EC_PRIVATEKEY, version, LONG),
    //   ASN1_SIMPLE(EC_PRIVATEKEY, privateKey, ASN1_OCTET_STRING),
    //   ASN1_EXP_OPT(EC_PRIVATEKEY, parameters, ECPKPARAMETERS, 0),
    //   ASN1_EXP_OPT(EC_PRIVATEKEY, publicKey, ASN1_BIT_STRING, 1)
    // } ASN1_SEQUENCE_END(EC_PRIVATEKEY)
    //
    try {
        ASN1InputStream decoder = new ASN1InputStream(asn1privkey);
        DLSequence seq = (DLSequence) decoder.readObject();
        checkArgument(seq.size() == 4, "Input does not appear to be an ASN.1 OpenSSL EC private key");
        checkArgument(((DERInteger) seq.getObjectAt(0)).getValue().equals(BigInteger.ONE),
                "Input is of wrong version");
        Object obj = seq.getObjectAt(1);
        byte[] bits = ((ASN1OctetString) obj).getOctets();
        decoder.close();
        return new BigInteger(1, bits);
    } catch (IOException e) {
        throw new RuntimeException(e); // Cannot happen, reading from memory stream.
    }
}