Search in sources :

Example 26 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project robovm by robovm.

the class CertPathValidatorUtilities method getAlgorithmIdentifier.

protected static AlgorithmIdentifier getAlgorithmIdentifier(PublicKey key) throws CertPathValidatorException {
    try {
        ASN1InputStream aIn = new ASN1InputStream(key.getEncoded());
        SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());
        return info.getAlgorithmId();
    } catch (Exception e) {
        throw new ExtCertPathValidatorException("Subject public key cannot be decoded.", e);
    }
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) ParseException(java.text.ParseException) ExtCertPathValidatorException(org.bouncycastle.jce.exception.ExtCertPathValidatorException) CertStoreException(java.security.cert.CertStoreException) CRLException(java.security.cert.CRLException) CertificateParsingException(java.security.cert.CertificateParsingException) StoreException(org.bouncycastle.util.StoreException) IOException(java.io.IOException)

Example 27 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project robovm by robovm.

the class X509CertificateObject method toString.

public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = System.getProperty("line.separator");
    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);
    byte[] sig = this.getSignature();
    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
        if (i < sig.length - 20) {
            buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
        } else {
            buf.append("                       ").append(new String(Hex.encode(sig, i, sig.length - i))).append(nl);
        }
    }
    Extensions extensions = c.getTBSCertificate().getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        if (e.hasMoreElements()) {
            buf.append("       Extensions: \n");
        }
        while (e.hasMoreElements()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
            Extension ext = extensions.getExtension(oid);
            if (ext.getExtnValue() != null) {
                byte[] octs = ext.getExtnValue().getOctets();
                ASN1InputStream dIn = new ASN1InputStream(octs);
                buf.append("                       critical(").append(ext.isCritical()).append(") ");
                try {
                    if (oid.equals(Extension.basicConstraints)) {
                        buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(Extension.keyUsage)) {
                        buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
                        buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
                        buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
                    } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
                        buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
                    } else {
                        buf.append(oid.getId());
                        buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
                    //buf.append(" value = ").append("*****").append(nl);
                    }
                } catch (Exception ex) {
                    buf.append(oid.getId());
                    //     buf.append(" value = ").append(new String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl);
                    buf.append(" value = ").append("*****").append(nl);
                }
            } else {
                buf.append(nl);
            }
        }
    }
    return buf.toString();
}
Also used : VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) NetscapeRevocationURL(org.bouncycastle.asn1.misc.NetscapeRevocationURL) DERBitString(org.bouncycastle.asn1.DERBitString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1String(org.bouncycastle.asn1.ASN1String) Extensions(org.bouncycastle.asn1.x509.Extensions) CertificateExpiredException(java.security.cert.CertificateExpiredException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) NoSuchProviderException(java.security.NoSuchProviderException) Extension(org.bouncycastle.asn1.x509.Extension) VerisignCzagExtension(org.bouncycastle.asn1.misc.VerisignCzagExtension) DERIA5String(org.bouncycastle.asn1.DERIA5String) NetscapeCertType(org.bouncycastle.asn1.misc.NetscapeCertType) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 28 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project felix by apache.

the class CertificateUtil method createSelfSignedCert.

private static X509Certificate createSelfSignedCert(String commonName, KeyPair keypair) throws Exception {
    PublicKey publicKey = keypair.getPublic();
    String keyAlg = DPSigner.getSignatureAlgorithm(publicKey);
    X500Name issuer = new X500Name(commonName);
    BigInteger serial = BigInteger.probablePrime(16, new Random());
    Date notBefore = new Date(System.currentTimeMillis() - 1000);
    Date notAfter = new Date(notBefore.getTime() + 6000);
    SubjectPublicKeyInfo pubKeyInfo;
    try (ASN1InputStream is = new ASN1InputStream(publicKey.getEncoded())) {
        pubKeyInfo = SubjectPublicKeyInfo.getInstance(is.readObject());
    }
    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, pubKeyInfo);
    builder.addExtension(new Extension(Extension.basicConstraints, true, new DEROctetString(new BasicConstraints(false))));
    X509CertificateHolder certHolder = builder.build(new JcaContentSignerBuilder(keyAlg).build(keypair.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DEROctetString(org.bouncycastle.asn1.DEROctetString) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) DEROctetString(org.bouncycastle.asn1.DEROctetString) Extension(org.bouncycastle.asn1.x509.Extension) Random(java.util.Random) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 29 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project android_frameworks_base by crdroidandroid.

the class AndroidKeyStoreKeyPairGeneratorSpi method generateSelfSignedCertificateWithFakeSignature.

@SuppressWarnings("deprecation")
private X509Certificate generateSelfSignedCertificateWithFakeSignature(PublicKey publicKey) throws IOException, CertificateParsingException {
    V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator();
    ASN1ObjectIdentifier sigAlgOid;
    AlgorithmIdentifier sigAlgId;
    byte[] signature;
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_EC:
            sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid);
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(0));
            signature = new DERSequence().getEncoded();
            break;
        case KeymasterDefs.KM_ALGORITHM_RSA:
            sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption;
            sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE);
            signature = new byte[1];
            break;
        default:
            throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm);
    }
    try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) {
        tbsGenerator.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject()));
    }
    tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber()));
    X509Principal subject = new X509Principal(mSpec.getCertificateSubject().getEncoded());
    tbsGenerator.setSubject(subject);
    tbsGenerator.setIssuer(subject);
    tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore()));
    tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter()));
    tbsGenerator.setSignature(sigAlgId);
    TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate();
    ASN1EncodableVector result = new ASN1EncodableVector();
    result.add(tbsCertificate);
    result.add(sigAlgId);
    result.add(new DERBitString(signature));
    return new X509CertificateObject(Certificate.getInstance(new DERSequence(result)));
}
Also used : ASN1InputStream(com.android.org.bouncycastle.asn1.ASN1InputStream) ProviderException(java.security.ProviderException) Time(com.android.org.bouncycastle.asn1.x509.Time) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) AlgorithmIdentifier(com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) DERSequence(com.android.org.bouncycastle.asn1.DERSequence) X509CertificateObject(com.android.org.bouncycastle.jce.provider.X509CertificateObject) X509Principal(com.android.org.bouncycastle.jce.X509Principal) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) V3TBSCertificateGenerator(com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator) TBSCertificate(com.android.org.bouncycastle.asn1.x509.TBSCertificate) ASN1ObjectIdentifier(com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 30 with ASN1InputStream

use of com.android.org.bouncycastle.asn1.ASN1InputStream in project android_frameworks_base by AOSPA.

the class ESTHandler method execute.

public void execute(boolean reenroll) throws IOException, GeneralSecurityException {
    URL caURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + CACERT_PATH);
    HTTPResponse response;
    try (HTTPHandler httpHandler = new HTTPHandler(StandardCharsets.ISO_8859_1, mSocketFactory, mUser, mPassword)) {
        response = httpHandler.doGetHTTP(caURL);
        if (!"application/pkcs7-mime".equals(response.getHeaders().get(HTTPMessage.ContentTypeHeader))) {
            throw new IOException("Unexpected Content-Type: " + response.getHeaders().get(HTTPMessage.ContentTypeHeader));
        }
        ByteBuffer octetBuffer = response.getBinaryPayload();
        Collection<Asn1Object> pkcs7Content1 = Asn1Decoder.decode(octetBuffer);
        for (Asn1Object asn1Object : pkcs7Content1) {
            Log.d(TAG, "---");
            Log.d(TAG, asn1Object.toString());
        }
        Log.d(TAG, CACERT_PATH);
        mCACerts.addAll(unpackPkcs7(octetBuffer));
        for (X509Certificate certificate : mCACerts) {
            Log.d(TAG, "CA-Cert: " + certificate.getSubjectX500Principal());
        }
        /*
            byte[] octets = new byte[octetBuffer.remaining()];
            octetBuffer.duplicate().get(octets);
            for (byte b : octets) {
                System.out.printf("%02x ", b & 0xff);
            }
            Log.d(TAG, );
            */
        /* + BC
            try {
                byte[] octets = new byte[octetBuffer.remaining()];
                octetBuffer.duplicate().get(octets);
                ASN1InputStream asnin = new ASN1InputStream(octets);
                for (int n = 0; n < 100; n++) {
                    ASN1Primitive object = asnin.readObject();
                    if (object == null) {
                        break;
                    }
                    parseObject(object, 0);
                }
            }
            catch (Throwable t) {
                t.printStackTrace();
            }

            Collection<Asn1Object> pkcs7Content = Asn1Decoder.decode(octetBuffer);
            for (Asn1Object asn1Object : pkcs7Content) {
                Log.d(TAG, asn1Object);
            }

            if (pkcs7Content.size() != 1) {
                throw new IOException("Unexpected pkcs 7 container: " + pkcs7Content.size());
            }

            Asn1Constructed pkcs7Root = (Asn1Constructed) pkcs7Content.iterator().next();
            Iterator<Asn1ID> certPath = Arrays.asList(Pkcs7CertPath).iterator();
            Asn1Object certObject = pkcs7Root.findObject(certPath);
            if (certObject == null || certPath.hasNext()) {
                throw new IOException("Failed to find cert; returned object " + certObject +
                        ", path " + (certPath.hasNext() ? "short" : "exhausted"));
            }

            ByteBuffer certOctets = certObject.getPayload();
            if (certOctets == null) {
                throw new IOException("No cert payload in: " + certObject);
            }

            byte[] certBytes = new byte[certOctets.remaining()];
            certOctets.get(certBytes);

            CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
            Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(certBytes));
            Log.d(TAG, "EST Cert: " + cert);
            */
        URL csrURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + CSR_PATH);
        response = httpHandler.doGetHTTP(csrURL);
        octetBuffer = response.getBinaryPayload();
        byte[] csrData = buildCSR(octetBuffer, mOMADMAdapter, httpHandler);
        /**/
        Collection<Asn1Object> o = Asn1Decoder.decode(ByteBuffer.wrap(csrData));
        Log.d(TAG, "CSR:");
        Log.d(TAG, o.iterator().next().toString());
        Log.d(TAG, "End CSR.");
        /**/
        URL enrollURL = new URL(mURL.getProtocol(), mURL.getHost(), mURL.getPort(), mURL.getFile() + (reenroll ? SIMPLE_REENROLL_PATH : SIMPLE_ENROLL_PATH));
        String data = Base64.encodeToString(csrData, Base64.DEFAULT);
        octetBuffer = httpHandler.exchangeBinary(enrollURL, data, "application/pkcs10");
        Collection<Asn1Object> pkcs7Content2 = Asn1Decoder.decode(octetBuffer);
        for (Asn1Object asn1Object : pkcs7Content2) {
            Log.d(TAG, "---");
            Log.d(TAG, asn1Object.toString());
        }
        mClientCerts.addAll(unpackPkcs7(octetBuffer));
        for (X509Certificate cert : mClientCerts) {
            Log.d(TAG, cert.toString());
        }
    }
}
Also used : HTTPHandler(com.android.hotspot2.osu.HTTPHandler) HTTPResponse(com.android.hotspot2.utils.HTTPResponse) IOException(java.io.IOException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) ByteBuffer(java.nio.ByteBuffer) URL(java.net.URL) X509Certificate(java.security.cert.X509Certificate) Asn1Object(com.android.hotspot2.asn1.Asn1Object)

Aggregations

ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)108 IOException (java.io.IOException)90 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)36 ByteArrayInputStream (java.io.ByteArrayInputStream)35 X509Certificate (java.security.cert.X509Certificate)25 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)25 BigInteger (java.math.BigInteger)21 DEROctetString (org.bouncycastle.asn1.DEROctetString)21 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)20 CertificateException (java.security.cert.CertificateException)20 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18 CertificateParsingException (java.security.cert.CertificateParsingException)18 Enumeration (java.util.Enumeration)17 CertificateEncodingException (java.security.cert.CertificateEncodingException)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 InvalidKeyException (java.security.InvalidKeyException)14 CRLException (java.security.cert.CRLException)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 ASN1Primitive (org.bouncycastle.asn1.ASN1Primitive)12 NoSuchProviderException (java.security.NoSuchProviderException)11