Search in sources :

Example 21 with AlgorithmIdentifier

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

the class X509CertSelector method match.

/**
     * Returns whether the specified certificate matches all the criteria
     * collected in this instance.
     *
     * @param certificate
     *            the certificate to check.
     * @return {@code true} if the certificate matches all the criteria,
     *         otherwise {@code false}.
     */
public boolean match(Certificate certificate) {
    if (!(certificate instanceof X509Certificate)) {
        return false;
    }
    X509Certificate cert = (X509Certificate) certificate;
    if ((certificateEquals != null) && !certificateEquals.equals(cert)) {
        return false;
    }
    if ((serialNumber != null) && !serialNumber.equals(cert.getSerialNumber())) {
        return false;
    }
    if ((issuer != null) && !issuer.equals(cert.getIssuerX500Principal())) {
        return false;
    }
    if ((subject != null) && !subject.equals(cert.getSubjectX500Principal())) {
        return false;
    }
    if ((subjectKeyIdentifier != null) && !Arrays.equals(subjectKeyIdentifier, // are taken from rfc 3280 (http://www.ietf.org/rfc/rfc3280.txt)
    getExtensionValue(cert, "2.5.29.14"))) {
        return false;
    }
    if ((authorityKeyIdentifier != null) && !Arrays.equals(authorityKeyIdentifier, getExtensionValue(cert, "2.5.29.35"))) {
        return false;
    }
    if (certificateValid != null) {
        try {
            cert.checkValidity(certificateValid);
        } catch (CertificateExpiredException e) {
            return false;
        } catch (CertificateNotYetValidException e) {
            return false;
        }
    }
    if (privateKeyValid != null) {
        try {
            byte[] bytes = getExtensionValue(cert, "2.5.29.16");
            if (bytes == null) {
                return false;
            }
            PrivateKeyUsagePeriod pkup = (PrivateKeyUsagePeriod) PrivateKeyUsagePeriod.ASN1.decode(bytes);
            Date notBefore = pkup.getNotBefore();
            Date notAfter = pkup.getNotAfter();
            if ((notBefore == null) && (notAfter == null)) {
                return false;
            }
            if ((notBefore != null) && notBefore.compareTo(privateKeyValid) > 0) {
                return false;
            }
            if ((notAfter != null) && notAfter.compareTo(privateKeyValid) < 0) {
                return false;
            }
        } catch (IOException e) {
            return false;
        }
    }
    if (subjectPublicKeyAlgID != null) {
        try {
            byte[] encoding = cert.getPublicKey().getEncoded();
            AlgorithmIdentifier ai = ((SubjectPublicKeyInfo) SubjectPublicKeyInfo.ASN1.decode(encoding)).getAlgorithmIdentifier();
            if (!subjectPublicKeyAlgID.equals(ai.getAlgorithm())) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    if (subjectPublicKey != null) {
        if (!Arrays.equals(subjectPublicKey, cert.getPublicKey().getEncoded())) {
            return false;
        }
    }
    if (keyUsage != null) {
        boolean[] ku = cert.getKeyUsage();
        if (ku != null) {
            int i = 0;
            int min_length = (ku.length < keyUsage.length) ? ku.length : keyUsage.length;
            for (; i < min_length; i++) {
                if (keyUsage[i] && !ku[i]) {
                    // but certificate does not.
                    return false;
                }
            }
            for (; i < keyUsage.length; i++) {
                if (keyUsage[i]) {
                    return false;
                }
            }
        }
    }
    if (extendedKeyUsage != null) {
        try {
            List keyUsage = cert.getExtendedKeyUsage();
            if (keyUsage != null) {
                if (!keyUsage.containsAll(extendedKeyUsage)) {
                    return false;
                }
            }
        } catch (CertificateParsingException e) {
            return false;
        }
    }
    if (pathLen != -1) {
        int p_len = cert.getBasicConstraints();
        if ((pathLen < 0) && (p_len >= 0)) {
            // need end-entity but got CA
            return false;
        }
        if ((pathLen > 0) && (pathLen > p_len)) {
            // allowed _pathLen is small
            return false;
        }
    }
    if (subjectAltNames != null) {
        PASSED: try {
            byte[] bytes = getExtensionValue(cert, "2.5.29.17");
            if (bytes == null) {
                return false;
            }
            List<GeneralName> sans = ((GeneralNames) GeneralNames.ASN1.decode(bytes)).getNames();
            if ((sans == null) || (sans.size() == 0)) {
                return false;
            }
            boolean[][] map = new boolean[9][];
            // initialize the check map
            for (int i = 0; i < 9; i++) {
                map[i] = (subjectAltNames[i] == null) ? EmptyArray.BOOLEAN : new boolean[subjectAltNames[i].size()];
            }
            for (GeneralName name : sans) {
                int tag = name.getTag();
                for (int i = 0; i < map[tag].length; i++) {
                    if (subjectAltNames[tag].get(i).equals(name)) {
                        if (!matchAllNames) {
                            break PASSED;
                        }
                        map[tag][i] = true;
                    }
                }
            }
            if (!matchAllNames) {
                // there was not any match
                return false;
            }
            // else check the map
            for (int tag = 0; tag < 9; tag++) {
                for (int name = 0; name < map[tag].length; name++) {
                    if (!map[tag][name]) {
                        return false;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    if (nameConstraints != null) {
        if (!nameConstraints.isAcceptable(cert)) {
            return false;
        }
    }
    if (policies != null) {
        byte[] bytes = getExtensionValue(cert, "2.5.29.32");
        if (bytes == null) {
            return false;
        }
        if (policies.size() == 0) {
            // one policy in it.
            return true;
        }
        PASSED: try {
            List<PolicyInformation> policyInformations = ((CertificatePolicies) CertificatePolicies.ASN1.decode(bytes)).getPolicyInformations();
            for (PolicyInformation policyInformation : policyInformations) {
                if (policies.contains(policyInformation.getPolicyIdentifier())) {
                    break PASSED;
                }
            }
            return false;
        } catch (IOException e) {
            // the extension is invalid
            return false;
        }
    }
    if (pathToNames != null) {
        byte[] bytes = getExtensionValue(cert, "2.5.29.30");
        if (bytes != null) {
            NameConstraints nameConstraints;
            try {
                nameConstraints = (NameConstraints) NameConstraints.ASN1.decode(bytes);
            } catch (IOException e) {
                // the extension is invalid;
                return false;
            }
            if (!nameConstraints.isAcceptable(pathToNames)) {
                return false;
            }
        }
    }
    return true;
}
Also used : NameConstraints(org.apache.harmony.security.x509.NameConstraints) PolicyInformation(org.apache.harmony.security.x509.PolicyInformation) IOException(java.io.IOException) SubjectPublicKeyInfo(org.apache.harmony.security.x509.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.apache.harmony.security.x509.AlgorithmIdentifier) ArrayList(java.util.ArrayList) List(java.util.List) GeneralName(org.apache.harmony.security.x509.GeneralName) PrivateKeyUsagePeriod(org.apache.harmony.security.x509.PrivateKeyUsagePeriod)

Example 22 with AlgorithmIdentifier

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

the class SubjectPublicKeyInfoTest method test_getPublicKey_NameKnownButOnlyOIDFactoryRegistered.

public void test_getPublicKey_NameKnownButOnlyOIDFactoryRegistered() throws Exception {
    Security.addProvider(new MyTestProvider());
    try {
        AlgorithmIdentifier algid = new AlgorithmIdentifier(MY_TEST_KEY_OID, "UnknownKey");
        SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algid, ENCODED_BROKEN);
        PublicKey pubKey = spki.getPublicKey();
        assertNotNull(pubKey);
        assertEquals(MyTestPublicKey.class, pubKey.getClass());
        byte[] encoded = pubKey.getEncoded();
        assertEquals(Arrays.toString(ENCODED_BROKEN), Arrays.toString(Arrays.copyOfRange(encoded, encoded.length - ENCODED_BROKEN.length, encoded.length)));
    } finally {
        Security.removeProvider(MyTestProvider.NAME);
    }
}
Also used : X509PublicKey(org.apache.harmony.security.x509.X509PublicKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) SubjectPublicKeyInfo(org.apache.harmony.security.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.apache.harmony.security.x509.AlgorithmIdentifier)

Example 23 with AlgorithmIdentifier

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

the class SubjectPublicKeyInfoTest method test_getPublicKey_Unknown_OID.

public void test_getPublicKey_Unknown_OID() throws Exception {
    AlgorithmIdentifier algid = new AlgorithmIdentifier("1.30.9999999999.8734878");
    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo(algid, ENCODED_BROKEN);
    PublicKey pubKey = spki.getPublicKey();
    assertNotNull(pubKey);
    assertEquals(X509PublicKey.class, pubKey.getClass());
}
Also used : X509PublicKey(org.apache.harmony.security.x509.X509PublicKey) PublicKey(java.security.PublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) SubjectPublicKeyInfo(org.apache.harmony.security.x509.SubjectPublicKeyInfo) AlgorithmIdentifier(org.apache.harmony.security.x509.AlgorithmIdentifier)

Example 24 with AlgorithmIdentifier

use of com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier 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 25 with AlgorithmIdentifier

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

the class PublicKeyFactory method createKey.

/**
     * Create a public key from the passed in SubjectPublicKeyInfo
     * 
     * @param keyInfo the SubjectPublicKeyInfo containing the key data
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithm();
    if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getAlgorithm().equals(X509ObjectIdentifiers.id_ea_rsa)) {
        RSAPublicKey pubKey = RSAPublicKey.getInstance(keyInfo.parsePublicKey());
        return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.dhpublicnumber)) {
        DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.parsePublicKey());
        BigInteger y = dhPublicKey.getY().getValue();
        DHDomainParameters dhParams = DHDomainParameters.getInstance(algId.getParameters());
        BigInteger p = dhParams.getP().getValue();
        BigInteger g = dhParams.getG().getValue();
        BigInteger q = dhParams.getQ().getValue();
        BigInteger j = null;
        if (dhParams.getJ() != null) {
            j = dhParams.getJ().getValue();
        }
        DHValidationParameters validation = null;
        DHValidationParms dhValidationParms = dhParams.getValidationParms();
        if (dhValidationParms != null) {
            byte[] seed = dhValidationParms.getSeed().getBytes();
            BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();
            // TODO Check pgenCounter size?
            validation = new DHValidationParameters(seed, pgenCounter.intValue());
        }
        return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getAlgorithm().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = DHParameter.getInstance(algId.getParameters());
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPublicKeyParameters(derY.getValue(), dhParams);
    } else // END android-removed
    if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_dsa) || algId.getAlgorithm().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
        ASN1Integer derY = (ASN1Integer) keyInfo.parsePublicKey();
        ASN1Encodable de = algId.getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.toASN1Primitive());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getAlgorithm().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((ASN1Primitive) algId.getParameters());
        X9ECParameters x9;
        if (params.isNamedCurve()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) params.getParameters();
            x9 = X962NamedCurves.getByOID(oid);
            if (x9 == null) {
                x9 = SECNamedCurves.getByOID(oid);
                if (x9 == null) {
                    x9 = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (x9 == null)
                // {
                //     x9 = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
        } else {
            x9 = X9ECParameters.getInstance(params.getParameters());
        }
        ASN1OctetString key = new DEROctetString(keyInfo.getPublicKeyData().getBytes());
        X9ECPoint derQ = new X9ECPoint(x9.getCurve(), key);
        // TODO We lose any named parameters here
        ECDomainParameters dParams = new ECDomainParameters(x9.getCurve(), x9.getG(), x9.getN(), x9.getH(), x9.getSeed());
        return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DHPublicKeyParameters(org.bouncycastle.crypto.params.DHPublicKeyParameters) ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHPublicKey(org.bouncycastle.asn1.x9.DHPublicKey) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) DHValidationParms(org.bouncycastle.asn1.x9.DHValidationParms) ECPublicKeyParameters(org.bouncycastle.crypto.params.ECPublicKeyParameters) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) RSAPublicKey(org.bouncycastle.asn1.pkcs.RSAPublicKey) DHValidationParameters(org.bouncycastle.crypto.params.DHValidationParameters) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) BigInteger(java.math.BigInteger) DHDomainParameters(org.bouncycastle.asn1.x9.DHDomainParameters) DSAParameters(org.bouncycastle.crypto.params.DSAParameters) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Aggregations

AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)31 IOException (java.io.IOException)18 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)11 DERObjectIdentifier (org.bouncycastle.asn1.DERObjectIdentifier)11 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)10 X962Parameters (org.bouncycastle.asn1.x9.X962Parameters)10 X9ECParameters (org.bouncycastle.asn1.x9.X9ECParameters)10 BigInteger (java.math.BigInteger)9 X509Certificate (java.security.cert.X509Certificate)8 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)7 GeneralSecurityException (java.security.GeneralSecurityException)6 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)6 ECNamedCurveSpec (org.bouncycastle.jce.spec.ECNamedCurveSpec)6 ECCurve (org.bouncycastle.math.ec.ECCurve)6 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1InputStream (com.android.org.bouncycastle.asn1.ASN1InputStream)5 ASN1Integer (com.android.org.bouncycastle.asn1.ASN1Integer)5 ASN1ObjectIdentifier (com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier)5