Search in sources :

Example 91 with CertificateFactory

use of java.security.cert.CertificateFactory in project Conversations by siacs.

the class IqParser method verification.

public Pair<X509Certificate[], byte[]> verification(final IqPacket packet) {
    Element item = getItem(packet);
    Element verification = item != null ? item.findChild("verification", AxolotlService.PEP_PREFIX) : null;
    Element chain = verification != null ? verification.findChild("chain") : null;
    Element signature = verification != null ? verification.findChild("signature") : null;
    if (chain != null && signature != null) {
        List<Element> certElements = chain.getChildren();
        X509Certificate[] certificates = new X509Certificate[certElements.size()];
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            int i = 0;
            for (Element cert : certElements) {
                certificates[i] = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(Base64.decode(cert.getContent(), Base64.DEFAULT)));
                ++i;
            }
            return new Pair<>(certificates, Base64.decode(signature.getContent(), Base64.DEFAULT));
        } catch (CertificateException e) {
            return null;
        }
    } else {
        return null;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Element(eu.siacs.conversations.xml.Element) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) Pair(android.util.Pair)

Example 92 with CertificateFactory

use of java.security.cert.CertificateFactory in project helios by spotify.

the class CertificateAndPrivateKey method from.

public static CertificateAndPrivateKey from(final Path certPath, final Path keyPath) throws IOException, GeneralSecurityException {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final Certificate certificate;
    try (final InputStream is = Files.newInputStream(certPath)) {
        certificate = cf.generateCertificate(is);
    }
    final Object parsedPem;
    try (final BufferedReader br = Files.newBufferedReader(keyPath, Charset.defaultCharset())) {
        parsedPem = new PEMParser(br).readObject();
    }
    final PrivateKeyInfo keyInfo;
    if (parsedPem instanceof PEMKeyPair) {
        keyInfo = ((PEMKeyPair) parsedPem).getPrivateKeyInfo();
    } else if (parsedPem instanceof PrivateKeyInfo) {
        keyInfo = (PrivateKeyInfo) parsedPem;
    } else {
        throw new UnsupportedOperationException("Unable to parse x509 certificate.");
    }
    final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyInfo.getEncoded());
    final KeyFactory kf = KeyFactory.getInstance("RSA");
    return new CertificateAndPrivateKey(certificate, kf.generatePrivate(spec));
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) InputStream(java.io.InputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BufferedReader(java.io.BufferedReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) CertificateFactory(java.security.cert.CertificateFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) KeyFactory(java.security.KeyFactory) Certificate(java.security.cert.Certificate)

Example 93 with CertificateFactory

use of java.security.cert.CertificateFactory in project platform_frameworks_base by android.

the class AndroidKeyPairGeneratorTest method assertKeyPairCorrect.

private void assertKeyPairCorrect(KeyPair pair, String alias, String keyType, int keySize, AlgorithmParameterSpec spec, X500Principal dn, BigInteger serial, Date start, Date end) throws Exception {
    final PublicKey pubKey = pair.getPublic();
    assertNotNull("The PublicKey for the KeyPair should be not null", pubKey);
    assertEquals(keyType, pubKey.getAlgorithm());
    if ("EC".equalsIgnoreCase(keyType)) {
        assertEquals("Curve should be what was specified during initialization", keySize, ((ECPublicKey) pubKey).getParams().getCurve().getField().getFieldSize());
    } else if ("RSA".equalsIgnoreCase(keyType)) {
        RSAPublicKey rsaPubKey = (RSAPublicKey) pubKey;
        assertEquals("Modulus size should be what is specified during initialization", (keySize + 7) & ~7, (rsaPubKey.getModulus().bitLength() + 7) & ~7);
        if (spec != null) {
            RSAKeyGenParameterSpec params = (RSAKeyGenParameterSpec) spec;
            assertEquals((keySize + 7) & ~7, (params.getKeysize() + 7) & ~7);
            assertEquals(params.getPublicExponent(), rsaPubKey.getPublicExponent());
        }
    }
    final PrivateKey privKey = pair.getPrivate();
    assertNotNull("The PrivateKey for the KeyPair should be not null", privKey);
    assertEquals(keyType, privKey.getAlgorithm());
    if ("EC".equalsIgnoreCase(keyType)) {
        assertTrue("EC private key must be instanceof ECKey: " + privKey.getClass().getName(), privKey instanceof ECKey);
        assertEquals("Private and public key must have the same EC parameters", ((ECKey) pubKey).getParams(), ((ECKey) privKey).getParams());
    } else if ("RSA".equalsIgnoreCase(keyType)) {
        assertTrue("RSA private key must be instance of RSAKey: " + privKey.getClass().getName(), privKey instanceof RSAKey);
        assertEquals("Private and public key must have the same RSA modulus", ((RSAKey) pubKey).getModulus(), ((RSAKey) privKey).getModulus());
    }
    final byte[] userCertBytes = mAndroidKeyStore.get(Credentials.USER_CERTIFICATE + alias);
    assertNotNull("The user certificate should exist for the generated entry", userCertBytes);
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final Certificate userCert = cf.generateCertificate(new ByteArrayInputStream(userCertBytes));
    assertTrue("Certificate should be in X.509 format", userCert instanceof X509Certificate);
    final X509Certificate x509userCert = (X509Certificate) userCert;
    assertEquals("Public key used to sign certificate should have the same algorithm as in KeyPair", pubKey.getAlgorithm(), x509userCert.getPublicKey().getAlgorithm());
    assertEquals("PublicKey used to sign certificate should match one returned in KeyPair", pubKey, AndroidKeyStoreProvider.getAndroidKeyStorePublicKey(Credentials.USER_PRIVATE_KEY + alias, KeyStore.UID_SELF, x509userCert.getPublicKey().getAlgorithm(), x509userCert.getPublicKey().getEncoded()));
    assertEquals("The Subject DN should be the one passed into the params", dn, x509userCert.getSubjectDN());
    assertEquals("The Issuer DN should be the same as the Subject DN", dn, x509userCert.getIssuerDN());
    assertEquals("The Serial should be the one passed into the params", serial, x509userCert.getSerialNumber());
    assertDateEquals("The notBefore date should be the one passed into the params", start, x509userCert.getNotBefore());
    assertDateEquals("The notAfter date should be the one passed into the params", end, x509userCert.getNotAfter());
    // Assert that the cert's signature verifies using the public key from generated KeyPair
    x509userCert.verify(pubKey);
    // Assert that the cert's signature verifies using the public key from the cert itself.
    x509userCert.verify(x509userCert.getPublicKey());
    final byte[] caCerts = mAndroidKeyStore.get(Credentials.CA_CERTIFICATE + alias);
    assertNull("A list of CA certificates should not exist for the generated entry", caCerts);
    ExportResult exportResult = mAndroidKeyStore.exportKey(Credentials.USER_PRIVATE_KEY + alias, KeymasterDefs.KM_KEY_FORMAT_X509, null, null);
    assertEquals(KeyStore.NO_ERROR, exportResult.resultCode);
    final byte[] pubKeyBytes = exportResult.exportData;
    assertNotNull("The keystore should return the public key for the generated key", pubKeyBytes);
    assertTrue("Public key X.509 format should be as expected", Arrays.equals(pubKey.getEncoded(), pubKeyBytes));
}
Also used : RSAKey(java.security.interfaces.RSAKey) PrivateKey(java.security.PrivateKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) ECPublicKey(java.security.interfaces.ECPublicKey) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ECKey(java.security.interfaces.ECKey) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) ECPublicKey(java.security.interfaces.ECPublicKey) RSAPublicKey(java.security.interfaces.RSAPublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) ExportResult(android.security.keymaster.ExportResult)

Example 94 with CertificateFactory

use of java.security.cert.CertificateFactory in project platform_frameworks_base by android.

the class AndroidKeyStoreTest method testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure.

public void testKeyStore_SetKeyEntry_ProtectedKey_Encrypted_Failure() throws Exception {
    setupPassword();
    mKeyStore.load(null, null);
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate caCert = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_CA_1));
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
    final Certificate[] chain = new Certificate[2];
    chain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_USER_1));
    chain[1] = caCert;
    try {
        mKeyStore.setKeyEntry(TEST_ALIAS_1, privKey, "foo".toCharArray(), chain);
        fail("Should fail when a password is specified");
    } catch (KeyStoreException success) {
    }
}
Also used : PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyStoreException(java.security.KeyStoreException) CertificateFactory(java.security.cert.CertificateFactory) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 95 with CertificateFactory

use of java.security.cert.CertificateFactory in project platform_frameworks_base by android.

the class AndroidKeyStoreTest method testKeyStore_SetEntry_PrivateKeyEntry_RSA_Unencrypted_Success.

public void testKeyStore_SetEntry_PrivateKeyEntry_RSA_Unencrypted_Success() throws Exception {
    mKeyStore.load(null, null);
    KeyFactory keyFact = KeyFactory.getInstance("RSA");
    PrivateKey expectedKey = keyFact.generatePrivate(new PKCS8EncodedKeySpec(FAKE_RSA_KEY_1));
    final CertificateFactory f = CertificateFactory.getInstance("X.509");
    final Certificate[] expectedChain = new Certificate[2];
    expectedChain[0] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_USER_1));
    expectedChain[1] = f.generateCertificate(new ByteArrayInputStream(FAKE_RSA_CA_1));
    PrivateKeyEntry expected = new PrivateKeyEntry(expectedKey, expectedChain);
    mKeyStore.setEntry(TEST_ALIAS_1, expected, null);
    Entry actualEntry = mKeyStore.getEntry(TEST_ALIAS_1, null);
    assertNotNull("Retrieved entry should exist", actualEntry);
    assertTrue("Retrieved entry should be of type PrivateKeyEntry", actualEntry instanceof PrivateKeyEntry);
    PrivateKeyEntry actual = (PrivateKeyEntry) actualEntry;
    assertPrivateKeyEntryEquals(actual, "RSA", FAKE_RSA_KEY_1, FAKE_RSA_USER_1, FAKE_RSA_CA_1);
}
Also used : TrustedCertificateEntry(java.security.KeyStore.TrustedCertificateEntry) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) Entry(java.security.KeyStore.Entry) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) CertificateFactory(java.security.cert.CertificateFactory) PrivateKeyEntry(java.security.KeyStore.PrivateKeyEntry) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

CertificateFactory (java.security.cert.CertificateFactory)550 X509Certificate (java.security.cert.X509Certificate)409 ByteArrayInputStream (java.io.ByteArrayInputStream)372 Certificate (java.security.cert.Certificate)272 CertificateException (java.security.cert.CertificateException)120 KeyFactory (java.security.KeyFactory)103 PrivateKey (java.security.PrivateKey)93 InputStream (java.io.InputStream)92 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)86 IOException (java.io.IOException)80 KeyStore (java.security.KeyStore)77 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)67 Entry (java.security.KeyStore.Entry)59 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)59 KeyStoreException (java.security.KeyStoreException)49 ArrayList (java.util.ArrayList)49 FileInputStream (java.io.FileInputStream)47 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)35 File (java.io.File)23 HashSet (java.util.HashSet)21