Java Examples for android.security.KeyPairGeneratorSpec

The following java examples will help you to understand the usage of android.security.KeyPairGeneratorSpec. These source code samples are taken from different open source projects.

Example 1
Project: rebase-android-master  File: BlackBox.java View source code
/**
     * Creates a public and private key and stores it using the AndroidKeyStore,
     * so that only this application will be able to access the keys.
     */
@SuppressWarnings("deprecation")
public void createKeys() throws Exception {
    KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    keyStore.load(null);
    if (keyStore.containsAlias(alias)) {
        Log.d(TAG, "[containsAlias]");
        return;
    }
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(alias).setSubject(new X500Principal("CN=" + alias)).setSerialNumber(BigInteger.TEN).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, ANDROID_KEY_STORE);
    generator.initialize(spec);
    KeyPair keyPair = generator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
Example 2
Project: Couchbase-master  File: RSASecureTokenStore.java View source code
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void initializePrivateKey(Context context) {
    if (!hasKeyStore)
        return;
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (keyStore.containsAlias(alias))
            return;
    } catch (Exception ex) {
        Log.e(TAG, "Unable to open KeyStore", ex);
        return;
    }
    // Create the keys if necessary
    try {
        // https://developer.android.com/reference/android/security/KeyPairGeneratorSpec.Builder.html
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 1);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(alias).setSubject(new X500Principal("CN=" + alias)).setSerialNumber(BigInteger.valueOf(1337)).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEYPAIRGEN_ALGORITHM, "AndroidKeyStore");
        generator.initialize(spec);
        KeyPair keyPair = generator.generateKeyPair();
    } catch (Exception ex) {
        Log.e(TAG, "Unable to create new key", ex);
        return;
    }
}
Example 3
Project: android-BasicAndroidKeyStore-master  File: BasicAndroidKeyStoreFragment.java View source code
/**
     * Creates a public and private key and stores it using the Android Key Store, so that only
     * this application will be able to access the keys.
     */
public void createKeys(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    // BEGIN_INCLUDE(create_valid_dates)
    // Create a start and end time, for the validity range of the key pair that's about to be
    // generated.
    Calendar start = new GregorianCalendar();
    Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 1);
    //END_INCLUDE(create_valid_dates)
    // BEGIN_INCLUDE(create_keypair)
    // Initialize a KeyPair generator using the the intended algorithm (in this example, RSA
    // and the KeyStore.  This example uses the AndroidKeyStore.
    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(SecurityConstants.TYPE_RSA, SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    // END_INCLUDE(create_keypair)
    // BEGIN_INCLUDE(create_spec)
    // The KeyPairGeneratorSpec object is how parameters for your key pair are passed
    // to the KeyPairGenerator.
    AlgorithmParameterSpec spec;
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        // Below Android M, use the KeyPairGeneratorSpec.Builder.
        spec = new KeyPairGeneratorSpec.Builder(context).setAlias(// You'll use the alias later to retrieve the key.  It's a key for the key!
        mAlias).setSubject(// The subject used for the self-signed certificate of the generated pair
        new X500Principal("CN=" + mAlias)).setSerialNumber(// generated pair.
        BigInteger.valueOf(1337)).setStartDate(// Date range of validity for the generated pair.
        start.getTime()).setEndDate(end.getTime()).build();
    } else {
        // On Android M or above, use the KeyGenparameterSpec.Builder and specify permitted
        // properties  and restrictions of the key.
        spec = new KeyGenParameterSpec.Builder(mAlias, KeyProperties.PURPOSE_SIGN).setCertificateSubject(new X500Principal("CN=" + mAlias)).setDigests(KeyProperties.DIGEST_SHA256).setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1).setCertificateSerialNumber(BigInteger.valueOf(1337)).setCertificateNotBefore(start.getTime()).setCertificateNotAfter(end.getTime()).build();
    }
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();
    // END_INCLUDE(create_spec)
    Log.d(TAG, "Public Key is: " + kp.getPublic().toString());
}
Example 4
Project: GradleCodeLab-master  File: KeyStoreUsage.java View source code
@Override
protected Boolean doInBackground(String... params) {
    final String alias = params[0];
    try {
        /*
                 * Generate a new entry in the KeyStore by using the
                 * KeyPairGenerator API. We have to specify the attributes for a
                 * self-signed X.509 certificate here so the KeyStore can attach
                 * the public key part to it. It can be replaced later with a
                 * certificate signed by a Certificate Authority (CA) if needed.
                 */
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date end = cal.getTime();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext()).setAlias(alias).setStartDate(now).setEndDate(end).setSerialNumber(BigInteger.valueOf(1)).setSubject(new X500Principal("CN=test1")).build());
        KeyPair kp = kpg.generateKeyPair();
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    }
}
Example 5
Project: android_frameworks_base-master  File: AndroidKeyStoreKeyPairGeneratorSpi.java View source code
@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 (NullPointerExceptionIllegalArgumentException |  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 (IllegalArgumentExceptionIllegalStateException |  e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Example 6
Project: wigle-wifi-wardriving-master  File: TokenAccess.java View source code
/**
     * Initialization method - only intended for run at app onCreate
     * @param prefs preferences from root context
     * @param context root context
     * @return true if successful encryption takes place, else false.
     */
public static boolean checkMigrateKeystoreVersion(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...");
            KeyStore keyStore = KeyStore.getInstance(ANDROID_KEYSTORE);
            keyStore.load(null);
            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(//.setKeySize(4096)
                new X500Principal("CN=wigle")).setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(//TODO: does endDate for the generation cert => key expiration?
                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 (KeyStoreExceptionCertificateException | NoSuchAlgorithmException | IOException | NoSuchProviderException | InvalidAlgorithmParameterException | ProviderException |  ex) {
            MainActivity.error("Upgrade/init of token storage failed: ", ex);
            ex.printStackTrace();
            return false;
        } catch (Exception e) {
            MainActivity.error("Unexpected error in upgrade/init of token storage failed: ", e);
            e.printStackTrace();
            return false;
        }
    }
    return false;
}
Example 7
Project: scytale-master  File: Store.java View source code
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private KeyPair generateAndroidJellyAsymmetricKey(KeyProps keyProps) {
    try {
        KeyPairGeneratorSpec keySpec = keyPropsToKeyPairGeneratorSpec(keyProps);
        return generateAndroidAsymmetricKey(keyProps, keySpec);
    } catch (NoSuchAlgorithmExceptionNoSuchProviderException | InvalidAlgorithmParameterException |  e) {
        onException(e);
    }
    return null;
}
Example 8
Project: Secured-Preference-Store-master  File: EncryptionManager.java View source code
@SuppressWarnings("WrongConstant")
void generateRSAKeys(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException {
    if (!mStore.containsAlias(RSA_KEY_ALIAS)) {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 25);
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA, KEYSTORE_PROVIDER);
        KeyPairGeneratorSpec spec;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            spec = new KeyPairGeneratorSpec.Builder(context).setAlias(RSA_KEY_ALIAS).setKeySize(RSA_BIT_LENGTH).setKeyType(KEY_ALGORITHM_RSA).setEndDate(end.getTime()).setStartDate(start.getTime()).setSerialNumber(BigInteger.ONE).setSubject(new X500Principal("CN = Secured Preference Store, O = Devliving Online")).build();
        } else {
            spec = new KeyPairGeneratorSpec.Builder(context).setAlias(RSA_KEY_ALIAS).setEndDate(end.getTime()).setStartDate(start.getTime()).setSerialNumber(BigInteger.ONE).setSubject(new X500Principal("CN = Secured Preference Store, O = Devliving Online")).build();
        }
        keyGen.initialize(spec);
        keyGen.generateKeyPair();
    }
}
Example 9
Project: platform_frameworks_base-master  File: AndroidKeyStoreKeyPairGeneratorSpi.java View source code
@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 (NullPointerExceptionIllegalArgumentException |  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 (IllegalArgumentExceptionIllegalStateException |  e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Example 10
Project: AmazeFileManager-master  File: CryptUtil.java View source code
/**
         * Generates a RSA public/private key pair to encrypt AES key
         * @param context
         * @throws KeyStoreException
         * @throws CertificateException
         * @throws NoSuchAlgorithmException
         * @throws IOException
         * @throws NoSuchProviderException
         * @throws InvalidAlgorithmParameterException
         */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void generateKeyPair(Context context) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, InvalidAlgorithmParameterException {
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);
    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        // generate a RSA key pair to encrypt/decrypt AES key from preferences
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEY_STORE_ANDROID);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(KEY_ALIAS_AMAZE).setSubject(new X500Principal("CN=" + KEY_ALIAS_AMAZE)).setSerialNumber(BigInteger.TEN).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    }
}
Example 11
Project: Inspeckage-master  File: WebServer.java View source code
public KeyPair generateKeys(String alias) {
    KeyPair keyPair = null;
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 1);
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.M) {
            KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY).setCertificateSubject(new X500Principal("CN=Inspeckage, OU=ACPM, O=ACPM, C=BR")).setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512).setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1).setCertificateNotBefore(start.getTime()).setCertificateNotAfter(end.getTime()).setKeyValidityStart(start.getTime()).setKeyValidityEnd(end.getTime()).setKeySize(2048).setCertificateSerialNumber(BigInteger.valueOf(1)).build();
            keyGen.initialize(spec);
        } else {
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext).setAlias(alias).setSubject(new X500Principal("CN=Inspeckage, OU=ACPM, O=ACPM, C=BR")).setSerialNumber(BigInteger.valueOf(12345)).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
            keyGen.initialize(spec);
        }
        keyPair = keyGen.generateKeyPair();
    } catch (GeneralSecurityException e) {
        Log.d("Inspeckage_Exception: ", e.getMessage());
    }
    return keyPair;
}
Example 12
Project: ZeroKit-Android-SDK-master  File: Zerokit.java View source code
private void generateNewKey(@NonNull Context context, @NonNull String alias) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.add(Calendar.YEAR, 1);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(alias).setSubject(new X500Principal("CN=zerokit")).setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", ANDROID_KEYSTORE);
    generator.initialize(spec);
    generator.generateKeyPair();
}
Example 13
Project: couchbase-lite-android-master  File: RSASecureTokenStore.java View source code
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private void initializePrivateKey(Context context) {
    if (!hasKeyStore)
        return;
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (keyStore.containsAlias(alias))
            return;
    } catch (Exception ex) {
        Log.e(TAG, "Unable to open KeyStore", ex);
        return;
    }
    // Create the keys if necessary
    try {
        // https://developer.android.com/reference/android/security/KeyPairGeneratorSpec.Builder.html
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 1);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context).setAlias(alias).setSubject(new X500Principal("CN=" + alias)).setSerialNumber(BigInteger.valueOf(1337)).setStartDate(start.getTime()).setEndDate(end.getTime()).build();
        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEYPAIRGEN_ALGORITHM, "AndroidKeyStore");
        generator.initialize(spec);
        KeyPair keyPair = generator.generateKeyPair();
    } catch (Exception ex) {
        Log.e(TAG, "Unable to create new key", ex);
        return;
    }
}
Example 14
Project: ApkLauncher-master  File: KeyStoreUsage.java View source code
@Override
protected Boolean doInBackground(String... params) {
    final String alias = params[0];
    try {
        /*
                 * Generate a new entry in the KeyStore by using the
                 * KeyPairGenerator API. We have to specify the attributes for a
                 * self-signed X.509 certificate here so the KeyStore can attach
                 * the public key part to it. It can be replaced later with a
                 * certificate signed by a Certificate Authority (CA) if needed.
                 */
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date end = cal.getTime();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext()).setAlias(alias).setStartDate(now).setEndDate(end).setSerialNumber(BigInteger.valueOf(1)).setSubject(new X500Principal("CN=test1")).build());
        KeyPair kp = kpg.generateKeyPair();
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    }
}
Example 15
Project: android-sdk-sources-for-api-level-23-master  File: AndroidKeyStoreKeyPairGeneratorSpi.java View source code
@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 (NullPointerExceptionIllegalArgumentException |  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();
        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());
        } catch (IllegalArgumentExceptionIllegalStateException |  e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Example 16
Project: andevcon-2014-jl-master  File: KeyStoreUsage.java View source code
@Override
protected Boolean doInBackground(String... params) {
    final String alias = params[0];
    try {
        /*
                 * Generate a new entry in the KeyStore by using the
                 * KeyPairGenerator API. We have to specify the attributes for a
                 * self-signed X.509 certificate here so the KeyStore can attach
                 * the public key part to it. It can be replaced later with a
                 * certificate signed by a Certificate Authority (CA) if needed.
                 */
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date end = cal.getTime();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext()).setAlias(alias).setStartDate(now).setEndDate(end).setSerialNumber(BigInteger.valueOf(1)).setSubject(new X500Principal("CN=test1")).build());
        KeyPair kp = kpg.generateKeyPair();
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    }
}
Example 17
Project: felix-on-android-master  File: KeyStoreUsage.java View source code
@Override
protected Boolean doInBackground(String... params) {
    final String alias = params[0];
    try {
        /*
                 * Generate a new entry in the KeyStore by using the
                 * KeyPairGenerator API. We have to specify the attributes for a
                 * self-signed X.509 certificate here so the KeyStore can attach
                 * the public key part to it. It can be replaced later with a
                 * certificate signed by a Certificate Authority (CA) if needed.
                 */
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date end = cal.getTime();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext()).setAlias(alias).setStartDate(now).setEndDate(end).setSerialNumber(BigInteger.valueOf(1)).setSubject(new X500Principal("CN=test1")).build());
        KeyPair kp = kpg.generateKeyPair();
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    }
}
Example 18
Project: ApkLauncher_legacy-master  File: KeyStoreUsage.java View source code
@Override
protected Boolean doInBackground(String... params) {
    final String alias = params[0];
    try {
        /*
                 * Generate a new entry in the KeyStore by using the
                 * KeyPairGenerator API. We have to specify the attributes for a
                 * self-signed X.509 certificate here so the KeyStore can attach
                 * the public key part to it. It can be replaced later with a
                 * certificate signed by a Certificate Authority (CA) if needed.
                 */
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        cal.add(Calendar.YEAR, 1);
        Date end = cal.getTime();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
        kpg.initialize(new KeyPairGeneratorSpec.Builder(getApplicationContext()).setAlias(alias).setStartDate(now).setEndDate(end).setSerialNumber(BigInteger.valueOf(1)).setSubject(new X500Principal("CN=test1")).build());
        KeyPair kp = kpg.generateKeyPair();
        return true;
    } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    } catch (NoSuchProviderException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
    }
}
Example 19
Project: android-keystore-master  File: Crypto.java View source code
@SuppressLint("NewApi")
public static KeyPair generateRsaPairWithGenerator(Context ctx, String alais) throws Exception {
    Calendar notBefore = Calendar.getInstance();
    Calendar notAfter = Calendar.getInstance();
    notAfter.add(1, Calendar.YEAR);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx).setAlias(alais).setSubject(new X500Principal(String.format("CN=%s, OU=%s", alais, ctx.getPackageName()))).setSerialNumber(BigInteger.ONE).setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build();
    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();
    return kp;
}