Search in sources :

Example 1 with KeyPairGeneratorSpec

use of android.security.KeyPairGeneratorSpec in project android_frameworks_base by ResurrectionRemix.

the class AndroidKeyStoreKeyPairGeneratorSpi method initialize.

@SuppressWarnings("deprecation")
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException {
    resetAll();
    boolean success = false;
    try {
        if (params == null) {
            throw new InvalidAlgorithmParameterException("Must supply params of type " + KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName());
        }
        KeyGenParameterSpec spec;
        boolean encryptionAtRestRequired = false;
        int keymasterAlgorithm = mOriginalKeymasterAlgorithm;
        if (params instanceof KeyGenParameterSpec) {
            spec = (KeyGenParameterSpec) params;
        } else if (params instanceof KeyPairGeneratorSpec) {
            // Legacy/deprecated spec
            KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params;
            try {
                KeyGenParameterSpec.Builder specBuilder;
                String specKeyAlgorithm = legacySpec.getKeyType();
                if (specKeyAlgorithm != null) {
                    // Spec overrides the generator's default key algorithm
                    try {
                        keymasterAlgorithm = KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(specKeyAlgorithm);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidAlgorithmParameterException("Invalid key type in parameters", e);
                    }
                }
                switch(keymasterAlgorithm) {
                    case KeymasterDefs.KM_ALGORITHM_EC:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        // MD5 was never offered for Android Keystore for ECDSA.
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        break;
                    case KeymasterDefs.KM_ALGORITHM_RSA:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_MD5, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        // Authorized to be used with any encryption and signature padding
                        // schemes (including no padding).
                        specBuilder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                        specBuilder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                        // Disable randomized encryption requirement to support encryption
                        // padding NONE above.
                        specBuilder.setRandomizedEncryptionRequired(false);
                        break;
                    default:
                        throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
                }
                if (legacySpec.getKeySize() != -1) {
                    specBuilder.setKeySize(legacySpec.getKeySize());
                }
                if (legacySpec.getAlgorithmParameterSpec() != null) {
                    specBuilder.setAlgorithmParameterSpec(legacySpec.getAlgorithmParameterSpec());
                }
                specBuilder.setCertificateSubject(legacySpec.getSubjectDN());
                specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber());
                specBuilder.setCertificateNotBefore(legacySpec.getStartDate());
                specBuilder.setCertificateNotAfter(legacySpec.getEndDate());
                encryptionAtRestRequired = legacySpec.isEncryptionRequired();
                specBuilder.setUserAuthenticationRequired(false);
                spec = specBuilder.build();
            } catch (NullPointerException | IllegalArgumentException e) {
                throw new InvalidAlgorithmParameterException(e);
            }
        } else {
            throw new InvalidAlgorithmParameterException("Unsupported params class: " + params.getClass().getName() + ". Supported: " + KeyGenParameterSpec.class.getName() + ", " + KeyPairGeneratorSpec.class.getName());
        }
        mEntryAlias = spec.getKeystoreAlias();
        mEntryUid = spec.getUid();
        mSpec = spec;
        mKeymasterAlgorithm = keymasterAlgorithm;
        mEncryptionAtRestRequired = encryptionAtRestRequired;
        mKeySizeBits = spec.getKeySize();
        initAlgorithmSpecificParameters();
        if (mKeySizeBits == -1) {
            mKeySizeBits = getDefaultKeySize(keymasterAlgorithm);
        }
        checkValidKeySize(keymasterAlgorithm, mKeySizeBits);
        if (spec.getKeystoreAlias() == null) {
            throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
        }
        String jcaKeyAlgorithm;
        try {
            jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
            mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
            mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
            mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
            if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
                for (int keymasterPadding : mKeymasterEncryptionPaddings) {
                    if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
                        throw new InvalidAlgorithmParameterException("Randomized encryption (IND-CPA) required but may be violated" + " by padding scheme: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See " + KeyGenParameterSpec.class.getName() + " documentation.");
                    }
                }
            }
            mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings());
            if (spec.isDigestsSpecified()) {
                mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
            } else {
                mKeymasterDigests = EmptyArray.INT;
            }
            // Check that user authentication related parameters are acceptable. This method
            // will throw an IllegalStateException if there are issues (e.g., secure lock screen
            // not set up).
            KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec.isUserAuthenticationRequired(), mSpec.getUserAuthenticationValidityDurationSeconds(), mSpec.isUserAuthenticationValidWhileOnBody(), mSpec.isInvalidatedByBiometricEnrollment());
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ProviderException(java.security.ProviderException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

Example 2 with KeyPairGeneratorSpec

use of android.security.KeyPairGeneratorSpec in project android_frameworks_base by AOSPA.

the class AndroidKeyStoreKeyPairGeneratorSpi method initialize.

@SuppressWarnings("deprecation")
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException {
    resetAll();
    boolean success = false;
    try {
        if (params == null) {
            throw new InvalidAlgorithmParameterException("Must supply params of type " + KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName());
        }
        KeyGenParameterSpec spec;
        boolean encryptionAtRestRequired = false;
        int keymasterAlgorithm = mOriginalKeymasterAlgorithm;
        if (params instanceof KeyGenParameterSpec) {
            spec = (KeyGenParameterSpec) params;
        } else if (params instanceof KeyPairGeneratorSpec) {
            // Legacy/deprecated spec
            KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params;
            try {
                KeyGenParameterSpec.Builder specBuilder;
                String specKeyAlgorithm = legacySpec.getKeyType();
                if (specKeyAlgorithm != null) {
                    // Spec overrides the generator's default key algorithm
                    try {
                        keymasterAlgorithm = KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(specKeyAlgorithm);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidAlgorithmParameterException("Invalid key type in parameters", e);
                    }
                }
                switch(keymasterAlgorithm) {
                    case KeymasterDefs.KM_ALGORITHM_EC:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        // MD5 was never offered for Android Keystore for ECDSA.
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        break;
                    case KeymasterDefs.KM_ALGORITHM_RSA:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_MD5, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        // Authorized to be used with any encryption and signature padding
                        // schemes (including no padding).
                        specBuilder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                        specBuilder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                        // Disable randomized encryption requirement to support encryption
                        // padding NONE above.
                        specBuilder.setRandomizedEncryptionRequired(false);
                        break;
                    default:
                        throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
                }
                if (legacySpec.getKeySize() != -1) {
                    specBuilder.setKeySize(legacySpec.getKeySize());
                }
                if (legacySpec.getAlgorithmParameterSpec() != null) {
                    specBuilder.setAlgorithmParameterSpec(legacySpec.getAlgorithmParameterSpec());
                }
                specBuilder.setCertificateSubject(legacySpec.getSubjectDN());
                specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber());
                specBuilder.setCertificateNotBefore(legacySpec.getStartDate());
                specBuilder.setCertificateNotAfter(legacySpec.getEndDate());
                encryptionAtRestRequired = legacySpec.isEncryptionRequired();
                specBuilder.setUserAuthenticationRequired(false);
                spec = specBuilder.build();
            } catch (NullPointerException | IllegalArgumentException e) {
                throw new InvalidAlgorithmParameterException(e);
            }
        } else {
            throw new InvalidAlgorithmParameterException("Unsupported params class: " + params.getClass().getName() + ". Supported: " + KeyGenParameterSpec.class.getName() + ", " + KeyPairGeneratorSpec.class.getName());
        }
        mEntryAlias = spec.getKeystoreAlias();
        mEntryUid = spec.getUid();
        mSpec = spec;
        mKeymasterAlgorithm = keymasterAlgorithm;
        mEncryptionAtRestRequired = encryptionAtRestRequired;
        mKeySizeBits = spec.getKeySize();
        initAlgorithmSpecificParameters();
        if (mKeySizeBits == -1) {
            mKeySizeBits = getDefaultKeySize(keymasterAlgorithm);
        }
        checkValidKeySize(keymasterAlgorithm, mKeySizeBits);
        if (spec.isUseSecureProcessor()) {
            checkSecureProcessorValidKeySize(keymasterAlgorithm, mKeySizeBits);
        }
        if (spec.getKeystoreAlias() == null) {
            throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
        }
        String jcaKeyAlgorithm;
        try {
            jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
            mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
            mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
            mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
            if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
                for (int keymasterPadding : mKeymasterEncryptionPaddings) {
                    if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
                        throw new InvalidAlgorithmParameterException("Randomized encryption (IND-CPA) required but may be violated" + " by padding scheme: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See " + KeyGenParameterSpec.class.getName() + " documentation.");
                    }
                }
            }
            mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings());
            if (spec.isDigestsSpecified()) {
                mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
            } else {
                mKeymasterDigests = EmptyArray.INT;
            }
            // Check that user authentication related parameters are acceptable. This method
            // will throw an IllegalStateException if there are issues (e.g., secure lock screen
            // not set up).
            KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec.isUserAuthenticationRequired(), mSpec.getUserAuthenticationValidityDurationSeconds(), mSpec.isUserAuthenticationValidWhileOnBody(), mSpec.isInvalidatedByBiometricEnrollment());
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ProviderException(java.security.ProviderException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

Example 3 with KeyPairGeneratorSpec

use of android.security.KeyPairGeneratorSpec in project MGit by maks.

the class SecurePrefsHelper method generateKeyPair.

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
void generateKeyPair(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException {
    // Generate the RSA key pairs
    if (!mKeyStore.containsAlias(KEY_ALIAS)) {
        // Generate a key pair for encryption
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(KEY_ALIAS).setSubject(new X500Principal("CN=" + KEY_ALIAS)).setSerialNumber(BigInteger.TEN).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA, AndroidKeyStore);
        kpg.initialize(spec);
        kpg.generateKeyPair();
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) Calendar(java.util.Calendar) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) TargetApi(android.annotation.TargetApi)

Example 4 with KeyPairGeneratorSpec

use of android.security.KeyPairGeneratorSpec in project wigle-wifi-wardriving by wiglenet.

the class TokenAccess method checkMigrateKeystoreVersion1.

private static boolean checkMigrateKeystoreVersion1(SharedPreferences prefs, Context context) {
    boolean initOnly = false;
    if (prefs.getString(ListFragment.PREF_TOKEN, "").isEmpty()) {
        MainActivity.info("[TOKEN] No auth token stored - no preference migration possible.");
        initOnly = true;
    }
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
        // no reliable keystore here
        MainActivity.info("[TOKEN] No KeyStore support - no preference migration possible.");
        return false;
    } else {
        try {
            MainActivity.info("[TOKEN] Using Android Keystore; check need for new key...");
            final KeyStore keyStore = getKeyStore();
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEYSTORE);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                if (keyStore.containsAlias(KEYSTORE_WIGLE_CREDS_KEY_V1)) {
                    MainActivity.info("[TOKEN] Key present and up-to-date M - no change.");
                    return false;
                }
                MainActivity.info("[TOKEN] Initializing SDKv23 Key...");
                String token = "";
                if (keyStore.containsAlias(KEYSTORE_WIGLE_CREDS_KEY_V0)) {
                    // ALIBI: fetch token with V0 key if it's stored that way
                    token = TokenAccess.getApiToken(prefs);
                }
                KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(KEYSTORE_WIGLE_CREDS_KEY_V1, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT).setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP).build();
                kpg.initialize(spec);
                kpg.generateKeyPair();
                if (keyStore.containsAlias(KEYSTORE_WIGLE_CREDS_KEY_V0)) {
                    MainActivity.info("[TOKEN] Upgrading from v0->v1 token...");
                    if ((null == token) || token.isEmpty())
                        return false;
                    keyStore.deleteEntry(KEYSTORE_WIGLE_CREDS_KEY_V0);
                } else {
                    token = prefs.getString(ListFragment.PREF_TOKEN, "");
                    // DEBUG: MainActivity.info("[TOKEN] +"+token+"+");
                    MainActivity.info("[TOKEN] Encrypting token at v1...");
                    if (token.isEmpty()) {
                        MainActivity.info("[TOKEN] ...no token, returning after init.");
                        return false;
                    }
                }
                if (!initOnly) {
                    if (TokenAccess.setApiToken(prefs, token)) {
                        MainActivity.info("[TOKEN] ...token set at v1.");
                        return true;
                    } else {
                        /**
                         * ALIBI: if you can't migrate it, clear it to force re-authentication.
                         * this isn't optimal, but it beats the alternative.
                         * This is vital here, since Marshmallow and up can backup/restore
                         * SharedPreferences, but NOT keystore entries
                         */
                        MainActivity.error("[TOKEN] ...Failed token encryption; clearing.");
                        clearApiToken(prefs);
                    }
                } else {
                    MainActivity.error("[TOKEN] v1 Keystore initialized, but no token present.");
                }
            } else if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                if (keyStore.containsAlias(KEYSTORE_WIGLE_CREDS_KEY_V0)) {
                    MainActivity.info("[TOKEN] Key present and up-to-date JB-MR2 - no action required.");
                    return false;
                }
                MainActivity.info("[TOKEN] Initializing SDKv18 Key...");
                Calendar notBefore = Calendar.getInstance();
                Calendar notAfter = Calendar.getInstance();
                notAfter.add(Calendar.YEAR, 3);
                KeyPairGeneratorSpec spec = null;
                spec = new KeyPairGeneratorSpec.Builder(context).setAlias(KEYSTORE_WIGLE_CREDS_KEY_V0).setSubject(new X500Principal("CN=wigle")).setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();
                kpg.initialize(spec);
                kpg.generateKeyPair();
                String token = prefs.getString(ListFragment.PREF_TOKEN, "");
                if (token.isEmpty()) {
                    MainActivity.info("[TOKEN] ...no token, returning after init.");
                    return false;
                }
                MainActivity.info("[TOKEN] Encrypting token at v0...");
                if (!initOnly) {
                    if (TokenAccess.setApiToken(prefs, token)) {
                        MainActivity.info("[TOKEN] ...token set at v0.");
                        return true;
                    } else {
                        /**
                         * ALIBI: if you can't migrate it, clear it to force re-authentication.
                         * this isn't optimal, but it beats the alternative.
                         * This may not be necessary in the pre-Marshmallow world.
                         */
                        MainActivity.error("[TOKEN] ...Failed token encryption; clearing.");
                        clearApiToken(prefs);
                    }
                } else {
                    MainActivity.error("[TOKEN] v0 Keystore initialized, but no token present.");
                }
            }
        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | NoSuchProviderException | InvalidAlgorithmParameterException | ProviderException ex) {
            MainActivity.error("Upgrade/init of token storage failed: ", ex);
            ex.printStackTrace();
            // clearApiToken(prefs);
            return false;
        } catch (Exception e) {
            /**
             * ALIBI: after production evidence of a ProviderException (runtime), adding belt to
             * suspenders
             */
            MainActivity.error("Unexpected error in upgrade/init of token storage failed: ", e);
            e.printStackTrace();
            return false;
        }
    }
    return false;
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeyGenParameterSpec(android.security.keystore.KeyGenParameterSpec) ProviderException(java.security.ProviderException) NoSuchProviderException(java.security.NoSuchProviderException) Calendar(java.util.Calendar) CertificateException(java.security.cert.CertificateException) KeyPairGenerator(java.security.KeyPairGenerator) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) KeyStoreException(java.security.KeyStoreException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) ProviderException(java.security.ProviderException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException) X500Principal(javax.security.auth.x500.X500Principal) NoSuchProviderException(java.security.NoSuchProviderException)

Example 5 with KeyPairGeneratorSpec

use of android.security.KeyPairGeneratorSpec in project vialer-android by VoIPGRID.

the class AccountHelper method generateKeyPair.

/**
 * Function to generate a KeyPair used for encrypting/decrypting
 * @throws Exception
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeyPair() throws Exception {
    // Make sure this key is valid for a lifetime.
    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.add(Calendar.YEAR, 99);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext).setAlias(KEY_ALIAS).setSubject(new X500Principal("CN=" + KEY_ALIAS)).setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    generator.initialize(spec);
    // This will auto add them to the keystore.
    generator.generateKeyPair();
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) Calendar(java.util.Calendar) X500Principal(javax.security.auth.x500.X500Principal) KeyPairGenerator(java.security.KeyPairGenerator) TargetApi(android.annotation.TargetApi)

Aggregations

KeyPairGeneratorSpec (android.security.KeyPairGeneratorSpec)9 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)6 ProviderException (java.security.ProviderException)6 KeymasterArguments (android.security.keymaster.KeymasterArguments)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)5 KeyPairGenerator (java.security.KeyPairGenerator)4 Calendar (java.util.Calendar)4 X500Principal (javax.security.auth.x500.X500Principal)4 TargetApi (android.annotation.TargetApi)2 KeyGenParameterSpec (android.security.keystore.KeyGenParameterSpec)1 IOException (java.io.IOException)1 InvalidKeyException (java.security.InvalidKeyException)1 KeyPair (java.security.KeyPair)1 KeyStore (java.security.KeyStore)1 KeyStoreException (java.security.KeyStoreException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 NoSuchProviderException (java.security.NoSuchProviderException)1 UnrecoverableEntryException (java.security.UnrecoverableEntryException)1 CertificateException (java.security.cert.CertificateException)1