Search in sources :

Example 71 with PrivateKey

use of java.security.PrivateKey in project Conversations by siacs.

the class OtrService method saveKey.

private void saveKey() {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("DSA");
        DSAPrivateKeySpec privateKeySpec = keyFactory.getKeySpec(privateKey, DSAPrivateKeySpec.class);
        DSAPublicKeySpec publicKeySpec = keyFactory.getKeySpec(publicKey, DSAPublicKeySpec.class);
        this.account.setKey("otr_x", privateKeySpec.getX().toString(16));
        this.account.setKey("otr_g", privateKeySpec.getG().toString(16));
        this.account.setKey("otr_p", privateKeySpec.getP().toString(16));
        this.account.setKey("otr_q", privateKeySpec.getQ().toString(16));
        this.account.setKey("otr_y", publicKeySpec.getY().toString(16));
    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        e.printStackTrace();
    }
}
Also used : DSAPrivateKeySpec(java.security.spec.DSAPrivateKeySpec) PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyFactory(java.security.KeyFactory) DSAPublicKeySpec(java.security.spec.DSAPublicKeySpec)

Example 72 with PrivateKey

use of java.security.PrivateKey in project spring-boot by spring-projects.

the class TokenValidatorTests method getSignedToken.

private String getSignedToken(byte[] header, byte[] claims) throws Exception {
    PrivateKey privateKey = getPrivateKey();
    Signature signature = Signature.getInstance("SHA256WithRSA");
    signature.initSign(privateKey);
    byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims));
    signature.update(content);
    byte[] crypto = signature.sign();
    byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims), Base64Utils.encodeUrlSafe(crypto));
    return new String(token, UTF_8);
}
Also used : PrivateKey(java.security.PrivateKey) Signature(java.security.Signature)

Example 73 with PrivateKey

use of java.security.PrivateKey in project platform_frameworks_base by android.

the class AndroidKeyStoreRSACipherSpi method initKey.

@Override
protected final void initKey(int opmode, Key key) throws InvalidKeyException {
    if (key == null) {
        throw new InvalidKeyException("Unsupported key: null");
    }
    if (!KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(key.getAlgorithm())) {
        throw new InvalidKeyException("Unsupported key algorithm: " + key.getAlgorithm() + ". Only " + KeyProperties.KEY_ALGORITHM_RSA + " supported");
    }
    AndroidKeyStoreKey keystoreKey;
    if (key instanceof AndroidKeyStorePrivateKey) {
        keystoreKey = (AndroidKeyStoreKey) key;
    } else if (key instanceof AndroidKeyStorePublicKey) {
        keystoreKey = (AndroidKeyStoreKey) key;
    } else {
        throw new InvalidKeyException("Unsupported key type: " + key);
    }
    if (keystoreKey instanceof PrivateKey) {
        // Private key
        switch(opmode) {
            case Cipher.DECRYPT_MODE:
            case Cipher.UNWRAP_MODE:
                // Permitted
                break;
            case Cipher.ENCRYPT_MODE:
            case Cipher.WRAP_MODE:
                if (!adjustConfigForEncryptingWithPrivateKey()) {
                    throw new InvalidKeyException("RSA private keys cannot be used with " + opmodeToString(opmode) + " and padding " + KeyProperties.EncryptionPadding.fromKeymaster(mKeymasterPadding) + ". Only RSA public keys supported for this mode");
                }
                break;
            default:
                throw new InvalidKeyException("RSA private keys cannot be used with opmode: " + opmode);
        }
    } else {
        // Public key
        switch(opmode) {
            case Cipher.ENCRYPT_MODE:
            case Cipher.WRAP_MODE:
                // Permitted
                break;
            case Cipher.DECRYPT_MODE:
            case Cipher.UNWRAP_MODE:
                throw new InvalidKeyException("RSA public keys cannot be used with " + opmodeToString(opmode) + " and padding " + KeyProperties.EncryptionPadding.fromKeymaster(mKeymasterPadding) + ". Only RSA private keys supported for this opmode.");
            // break;
            default:
                throw new InvalidKeyException("RSA public keys cannot be used with " + opmodeToString(opmode));
        }
    }
    KeyCharacteristics keyCharacteristics = new KeyCharacteristics();
    int errorCode = getKeyStore().getKeyCharacteristics(keystoreKey.getAlias(), null, null, keystoreKey.getUid(), keyCharacteristics);
    if (errorCode != KeyStore.NO_ERROR) {
        throw getKeyStore().getInvalidKeyException(keystoreKey.getAlias(), keystoreKey.getUid(), errorCode);
    }
    long keySizeBits = keyCharacteristics.getUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, -1);
    if (keySizeBits == -1) {
        throw new InvalidKeyException("Size of key not known");
    } else if (keySizeBits > Integer.MAX_VALUE) {
        throw new InvalidKeyException("Key too large: " + keySizeBits + " bits");
    }
    mModulusSizeBytes = (int) ((keySizeBits + 7) / 8);
    setKey(keystoreKey);
}
Also used : PrivateKey(java.security.PrivateKey) KeyCharacteristics(android.security.keymaster.KeyCharacteristics) InvalidKeyException(java.security.InvalidKeyException)

Example 74 with PrivateKey

use of java.security.PrivateKey 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 75 with PrivateKey

use of java.security.PrivateKey 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)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46