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.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * Helper method that creates the BasicOCSPResp object.
 * @param seq// www. j a  va 2  s . co m
 * @throws IOException
 */
private void findOcsp(ASN1Sequence seq) throws IOException {
    basicResp = null;
    boolean ret = false;
    while (true) {
        if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier && ((ASN1ObjectIdentifier) seq.getObjectAt(0))
                .getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
            break;
        }
        ret = true;
        for (int k = 0; k < seq.size(); ++k) {
            if (seq.getObjectAt(k) instanceof ASN1Sequence) {
                seq = (ASN1Sequence) seq.getObjectAt(0);
                ret = false;
                break;
            }
            if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
                ASN1TaggedObject tag = (ASN1TaggedObject) seq.getObjectAt(k);
                if (tag.getObject() instanceof ASN1Sequence) {
                    seq = (ASN1Sequence) tag.getObject();
                    ret = false;
                    break;
                } else
                    return;
            }
        }
        if (ret)
            return;
    }
    ASN1OctetString os = (ASN1OctetString) seq.getObjectAt(1);
    ASN1InputStream inp = new ASN1InputStream(os.getOctets());
    BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
    basicResp = new BasicOCSPResp(resp);
}

From source file:com.jlocksmith.util.ExtensionUtil.java

License:Open Source License

/**
 * Gets a DER object from the given byte array.
 * /*w w w.j a  va2s  . c  om*/
 * @param bytes bytes
 * 
 * @return DERObject
 * 
 * @throws IOException if a conversion error occurs
 */
private static DERObject toDERObject(byte[] bytes) throws IOException {
    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(bytes));

    try {
        return in.readObject();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.leon.utils.sign.v2.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 {//from   www.j ava 2s. c  om
        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.
         */
        PrivateKeyInfo pki;
        try (ASN1InputStream bIn = new ASN1InputStream(new ByteArrayInputStream(spec.getEncoded()))) {
            pki = PrivateKeyInfo.getInstance(bIn.readObject());
        }
        String algOid = pki.getPrivateKeyAlgorithm().getAlgorithm().getId();

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

From source file:com.leon.utils.sign.v2.SignApk.java

License:Apache License

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

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

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

From source file:com.linkedin.mitm.services.AbstractX509CertificateService.java

License:Open Source License

/**
 * Create subjectKeyIdentifier//w ww  .j a  va2  s.co  m
 * The Subject Key Identifier extension identifies the public key certified by this certificate.
 * This extension provides a way of distinguishing public keys if more than one is available for
 * a given subject name.
 * i.e.
 *     Identifier: Subject Key Identifier - 2.5.29.14
 *       Critical: no
 *        Key Identifier:
 *          3B:46:83:85:27:BC:F5:9D:8E:63:E3:BE:79:EF:AF:79:
 *          9C:37:85:84
 *
 * */
protected SubjectKeyIdentifier createSubjectKeyIdentifier(PublicKey publicKey) throws IOException {
    try (ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
            ASN1InputStream ais = new ASN1InputStream(bais)) {
        ASN1Sequence asn1Sequence = (ASN1Sequence) ais.readObject();
        SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(asn1Sequence);
        return new BcX509ExtensionUtils().createSubjectKeyIdentifier(subjectPublicKeyInfo);
    }
}

From source file:com.motorolamobility.studio.android.certmanager.core.KeyStoreUtils.java

License:Apache License

/**
 * Create a new X509 certificate for a given KeyPair
 * @param keyPair the {@link KeyPair} used to create the certificate,
 *     RSAPublicKey and RSAPrivateKey are mandatory on keyPair, IllegalArgumentExeption will be thrown otherwise.
 * @param issuerName The issuer name to be used on the certificate
 * @param ownerName  The owner name to be used on the certificate
 * @param expireDate The expire date/*from  www  .ja v a 2s .c om*/
 * @return The {@link X509Certificate}
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 */
public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails)
        throws IOException, OperatorCreationException, CertificateException {

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) {
        throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected);
    }

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;

    //Transform the PublicKey into the BouncyCastle expected format
    ASN1InputStream asn1InputStream = null;
    X509Certificate x509Certificate = null;

    try {
        asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded()));
        SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());

        X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle());
        addField(BCStyle.C, certDetails.getCountry(), nameBuilder);
        addField(BCStyle.ST, certDetails.getState(), nameBuilder);
        addField(BCStyle.L, certDetails.getLocality(), nameBuilder);
        addField(BCStyle.O, certDetails.getOrganization(), nameBuilder);
        addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder);
        addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder);

        X500Name subjectName = nameBuilder.build();
        X500Name issuerName = subjectName;
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,
                BigInteger.valueOf(new SecureRandom().nextInt()), GregorianCalendar.getInstance().getTime(),
                certDetails.getExpirationDate(), subjectName, pubKey);

        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);

        //Create RSAKeyParameters, the private key format expected by Bouncy Castle
        RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(),
                rsaPrivateKey.getModulus());

        ContentSigner contentSigner = sigGen.build(keyParams);
        X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);

        //Convert the X509Certificate from BouncyCastle format to the java.security format
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        x509Certificate = certConverter.getCertificate(certificateHolder);
    } finally {
        if (asn1InputStream != null) {
            try {
                asn1InputStream.close();
            } catch (IOException e) {
                StudioLogger.error("Could not close stream while creating X509 certificate. " + e.getMessage());
            }
        }
    }

    return x509Certificate;
}

From source file:com.oneis.common.utils.SSLCertificates.java

License:Mozilla Public License

private static PrivateKey readPEMPrivateKey(String filename)
        throws java.io.IOException, java.security.GeneralSecurityException {
    ByteArrayInputStream bIn = readPEM(filename);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    if (!(seq.getObjectAt(1) instanceof DERInteger)) {
        throw new RuntimeException("Can't read RSA private key from " + filename
                + " - if file starts '-----BEGIN PRIVATE KEY-----' then it needs converting to RSA format with 'openssl rsa -in server-in.key -out server.key'.");
    }/* ww  w. j a v  a  2 s .  c o m*/
    DERInteger mod = (DERInteger) seq.getObjectAt(1);
    DERInteger pubExp = (DERInteger) seq.getObjectAt(2);
    DERInteger privExp = (DERInteger) seq.getObjectAt(3);
    DERInteger p1 = (DERInteger) seq.getObjectAt(4);
    DERInteger p2 = (DERInteger) seq.getObjectAt(5);
    DERInteger exp1 = (DERInteger) seq.getObjectAt(6);
    DERInteger exp2 = (DERInteger) seq.getObjectAt(7);
    DERInteger crtCoef = (DERInteger) seq.getObjectAt(8);

    RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(mod.getValue(), pubExp.getValue(),
            privExp.getValue(), p1.getValue(), p2.getValue(), exp1.getValue(), exp2.getValue(),
            crtCoef.getValue());

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(privSpec);
}

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

License:Mozilla Public License

/**
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key// ww  w. j a  v a  2s. c  o  m
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 */
public PDFEnvelopedSignature(byte[] contentsKey, byte[] certsKey, String provider, AcroFields acroFields,
        String signatureFieldName) {
    try {
        log.debug(Channel.TECH, "Verifying a adbe.x509.rsa_sha1 signature");
        this.acroFields = acroFields;
        this.signatureFieldName = signatureFieldName;
        this.subFilter = SF_ADBE_X509_RSA_SHA1;
        this.dictionaryCert = certsKey;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCert = (X509Certificate) certs.iterator().next();
        crls = new ArrayList();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        pkcs1SigValue = ((DEROctetString) in.readObject()).getOctets();

        Cipher c = Cipher.getInstance("RSA/NONE/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
        c.init(Cipher.DECRYPT_MODE, signCert);
        byte[] raw = c.doFinal(pkcs1SigValue);
        ASN1Sequence in3 = (ASN1Sequence) ASN1Object.fromByteArray(raw);
        DigestInfo di = DigestInfo.getInstance(in3);
        dataDigestAlgorithm = di.getAlgorithmId().getAlgorithm().getId();
        keyAndParameterAlgorithm = ID_RSA;

        if (provider == null)
            sig = Signature.getInstance(getSignatureAlgorithm());
        else
            sig = Signature.getInstance(getSignatureAlgorithm(), provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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   ww  w  .  ja  va 2s  . 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:com.peterphi.std.crypto.keygen.CaHelper.java

License:Open Source License

public static PKCS10CertificationRequest generateCertificateRequest(X509Certificate cert, PrivateKey signingKey)
        throws Exception {
    ASN1EncodableVector attributes = new ASN1EncodableVector();

    Set<String> nonCriticalExtensionOIDs = cert.getNonCriticalExtensionOIDs();
    for (String nceoid : nonCriticalExtensionOIDs) {
        byte[] derBytes = cert.getExtensionValue(nceoid);
        ByteArrayInputStream bis = new ByteArrayInputStream(derBytes);
        ASN1InputStream dis = new ASN1InputStream(bis);
        try {/* w ww  .  j  av a2 s.  com*/
            DERObject derObject = dis.readObject();
            DERSet value = new DERSet(derObject);
            Attribute attr = new Attribute(new DERObjectIdentifier(nceoid), value);
            attributes.add(attr);
        } finally {
            IOUtils.closeQuietly(dis);
        }
    }
    PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(getSignatureAlgorithm(),
            cert.getSubjectX500Principal(), cert.getPublicKey(), new DERSet(attributes), signingKey);
    return certificationRequest;
}