Search in sources :

Example 41 with KeyFactory

use of java.security.KeyFactory in project xabber-android by redsolution.

the class AccountTable method getKeyPair.

static KeyPair getKeyPair(Cursor cursor) {
    byte[] publicKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PUBLIC_KEY));
    byte[] privateKeyBytes = cursor.getBlob(cursor.getColumnIndex(Fields.PRIVATE_KEY));
    if (privateKeyBytes == null || publicKeyBytes == null) {
        return null;
    }
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    PublicKey publicKey;
    PrivateKey privateKey;
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("DSA");
        publicKey = keyFactory.generatePublic(publicKeySpec);
        privateKey = keyFactory.generatePrivate(privateKeySpec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new RuntimeException(e);
    }
    return new KeyPair(publicKey, privateKey);
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory)

Example 42 with KeyFactory

use of java.security.KeyFactory in project robovm by robovm.

the class ClientHandshakeImpl method processServerHelloDone.

/**
     * Processes ServerHelloDone: makes verification of the server messages; sends
     * client messages, computers masterSecret, sends ChangeCipherSpec
     */
void processServerHelloDone() {
    PrivateKey clientKey = null;
    if (serverCert != null) {
        if (session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
        verifyServerCert();
    } else {
        if (!session.cipherSuite.isAnonymous()) {
            unexpectedMessage();
            return;
        }
    }
    // Client certificate
    if (certificateRequest != null) {
        X509Certificate[] certs = null;
        // obtain certificates from key manager
        String alias = null;
        String[] certTypes = certificateRequest.getTypesAsString();
        X500Principal[] issuers = certificateRequest.certificate_authorities;
        X509KeyManager km = parameters.getKeyManager();
        if (km instanceof X509ExtendedKeyManager) {
            X509ExtendedKeyManager ekm = (X509ExtendedKeyManager) km;
            if (this.socketOwner != null) {
                alias = ekm.chooseClientAlias(certTypes, issuers, this.socketOwner);
            } else {
                alias = ekm.chooseEngineClientAlias(certTypes, issuers, this.engineOwner);
            }
            if (alias != null) {
                certs = ekm.getCertificateChain(alias);
            }
        } else {
            alias = km.chooseClientAlias(certTypes, issuers, this.socketOwner);
            if (alias != null) {
                certs = km.getCertificateChain(alias);
            }
        }
        session.localCertificates = certs;
        clientCert = new CertificateMessage(certs);
        clientKey = km.getPrivateKey(alias);
        send(clientCert);
    }
    // Client key exchange
    if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_RSA_EXPORT) {
        // RSA encrypted premaster secret message
        Cipher c;
        try {
            c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            if (serverKeyExchange != null) {
                if (!session.cipherSuite.isAnonymous()) {
                    DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                    ds.init(serverCert.certs[0]);
                    ds.update(clientHello.getRandom());
                    ds.update(serverHello.getRandom());
                    if (!serverKeyExchange.verifySignature(ds)) {
                        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify RSA params");
                        return;
                    }
                }
                c.init(Cipher.WRAP_MODE, serverKeyExchange.getRSAPublicKey());
            } else {
                c.init(Cipher.WRAP_MODE, serverCert.certs[0]);
            }
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
        preMasterSecret = new byte[48];
        parameters.getSecureRandom().nextBytes(preMasterSecret);
        System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0, 2);
        try {
            clientKeyExchange = new ClientKeyExchange(c.wrap(new SecretKeySpec(preMasterSecret, "preMasterSecret")), serverHello.server_version[1] == 1);
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else if (session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_DSS_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DHE_RSA_EXPORT || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon || session.cipherSuite.keyExchange == CipherSuite.KEY_EXCHANGE_DH_anon_EXPORT) {
        /*
             * All other key exchanges should have had a DH key communicated via
             * ServerKeyExchange beforehand.
             */
        if (serverKeyExchange == null) {
            fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "Expected ServerKeyExchange");
            return;
        }
        if (session.cipherSuite.isAnonymous() != serverKeyExchange.isAnonymous()) {
            fatalAlert(AlertProtocol.DECRYPT_ERROR, "Wrong type in ServerKeyExchange");
            return;
        }
        try {
            if (!session.cipherSuite.isAnonymous()) {
                DigitalSignature ds = new DigitalSignature(serverCert.getAuthType());
                ds.init(serverCert.certs[0]);
                ds.update(clientHello.getRandom());
                ds.update(serverHello.getRandom());
                if (!serverKeyExchange.verifySignature(ds)) {
                    fatalAlert(AlertProtocol.DECRYPT_ERROR, "Cannot verify DH params");
                    return;
                }
            }
            KeyFactory kf = KeyFactory.getInstance("DH");
            KeyAgreement agreement = KeyAgreement.getInstance("DH");
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
            PublicKey serverDhPublic = kf.generatePublic(new DHPublicKeySpec(serverKeyExchange.par3, serverKeyExchange.par1, serverKeyExchange.par2));
            DHParameterSpec spec = new DHParameterSpec(serverKeyExchange.par1, serverKeyExchange.par2);
            kpg.initialize(spec);
            KeyPair kp = kpg.generateKeyPair();
            DHPublicKey pubDhKey = (DHPublicKey) kp.getPublic();
            clientKeyExchange = new ClientKeyExchange(pubDhKey.getY());
            PrivateKey privDhKey = kp.getPrivate();
            agreement.init(privDhKey);
            agreement.doPhase(serverDhPublic, true);
            preMasterSecret = agreement.generateSecret();
        } catch (Exception e) {
            fatalAlert(AlertProtocol.INTERNAL_ERROR, "Unexpected exception", e);
            return;
        }
    } else {
        fatalAlert(AlertProtocol.DECRYPT_ERROR, "Unsupported handshake type");
        return;
    }
    if (clientKeyExchange != null) {
        send(clientKeyExchange);
    }
    computerMasterSecret();
    // fixed DH parameters
    if (clientCert != null && clientCert.certs.length > 0 && !clientKeyExchange.isEmpty()) {
        // Certificate verify
        String authType = clientKey.getAlgorithm();
        DigitalSignature ds = new DigitalSignature(authType);
        ds.init(clientKey);
        if ("RSA".equals(authType)) {
            ds.setMD5(io_stream.getDigestMD5());
            ds.setSHA(io_stream.getDigestSHA());
        } else if ("DSA".equals(authType)) {
            ds.setSHA(io_stream.getDigestSHA());
        // The Signature should be empty in case of anonymous signature algorithm:
        // } else if ("DH".equals(authType)) {
        }
        certificateVerify = new CertificateVerify(ds.sign());
        send(certificateVerify);
    }
    sendChangeCipherSpec();
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) PublicKey(java.security.PublicKey) DHPublicKey(javax.crypto.interfaces.DHPublicKey) DHParameterSpec(javax.crypto.spec.DHParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) X509ExtendedKeyManager(javax.net.ssl.X509ExtendedKeyManager) X509Certificate(java.security.cert.X509Certificate) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) X509KeyManager(javax.net.ssl.X509KeyManager) X500Principal(javax.security.auth.x500.X500Principal) Cipher(javax.crypto.Cipher) DHPublicKeySpec(javax.crypto.spec.DHPublicKeySpec) KeyAgreement(javax.crypto.KeyAgreement) KeyFactory(java.security.KeyFactory)

Example 43 with KeyFactory

use of java.security.KeyFactory in project hudson-2.x by hudson.

the class UsageStatistics method getCipher.

private Cipher getCipher() {
    try {
        if (key == null) {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            key = keyFactory.generatePublic(new X509EncodedKeySpec(Util.fromHexString(keyImage)));
        }
        Cipher cipher = Secret.getCipher("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher;
    } catch (GeneralSecurityException e) {
        // impossible
        throw new Error(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) Cipher(javax.crypto.Cipher) KeyFactory(java.security.KeyFactory)

Example 44 with KeyFactory

use of java.security.KeyFactory in project OpenAttestation by OpenAttestation.

the class X509Util method decodeDerPublicKey.

public static PublicKey decodeDerPublicKey(byte[] publicKeyBytes) throws CryptographyException {
    try {
        // throws NoSuchAlgorithmException
        KeyFactory factory = KeyFactory.getInstance("RSA");
        // throws InvalidKeySpecException
        PublicKey publicKey = factory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        return publicKey;
    } catch (Exception e) {
        throw new CryptographyException(e);
    }
}
Also used : PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) KeyFactory(java.security.KeyFactory) CertificateParsingException(java.security.cert.CertificateParsingException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 45 with KeyFactory

use of java.security.KeyFactory in project PushSms by koush.

the class MiddlewareService method getOrCreateKeyPair.

// create/read the keypair as necessary
private void getOrCreateKeyPair() {
    String encodedKeyPair = settings.getString("keypair", null);
    if (encodedKeyPair != null) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(encodedKeyPair, Base64.DEFAULT));
            ObjectInputStream in = new ObjectInputStream(bin);
            rsaPublicKeySpec = new RSAPublicKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec((BigInteger) in.readObject(), (BigInteger) (in.readObject()));
            PublicKey pub = keyFactory.generatePublic(rsaPublicKeySpec);
            PrivateKey priv = keyFactory.generatePrivate(rsaPrivateKeySpec);
            keyPair = new KeyPair(pub, priv);
            return;
        } catch (Exception e) {
            Log.e(LOGTAG, "KeyPair load error", e);
        }
    }
    try {
        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);
        keyPair = gen.generateKeyPair();
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        rsaPublicKeySpec = keyFactory.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
        RSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bout);
        out.writeObject(rsaPublicKeySpec.getModulus());
        out.writeObject(rsaPublicKeySpec.getPublicExponent());
        out.writeObject(privateKeySpec.getModulus());
        out.writeObject(privateKeySpec.getPrivateExponent());
        out.flush();
        settings.edit().putString("keypair", Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT)).commit();
        settings.edit().putBoolean("needs_register", true).commit();
    } catch (Exception e) {
        Log.wtf(LOGTAG, "KeyPair generation error", e);
        keyPair = null;
    }
}
Also used : KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) KeyPairGenerator(java.security.KeyPairGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) RemoteException(android.os.RemoteException) IOException(java.io.IOException) RSAPrivateKeySpec(java.security.spec.RSAPrivateKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) ObjectInputStream(java.io.ObjectInputStream)

Aggregations

KeyFactory (java.security.KeyFactory)425 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)187 PrivateKey (java.security.PrivateKey)181 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)125 PublicKey (java.security.PublicKey)125 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)119 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)109 CertificateFactory (java.security.cert.CertificateFactory)103 ByteArrayInputStream (java.io.ByteArrayInputStream)93 Certificate (java.security.cert.Certificate)89 X509Certificate (java.security.cert.X509Certificate)87 RSAPublicKeySpec (java.security.spec.RSAPublicKeySpec)62 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 IOException (java.io.IOException)53 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 BigInteger (java.math.BigInteger)47 RSAPublicKey (java.security.interfaces.RSAPublicKey)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)45 Signature (java.security.Signature)40