android.security.KeyPairGeneratorSpec Java Examples

The following examples show how to use android.security.KeyPairGeneratorSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a rsa key pair if it not exists.
 *
 * @param context the application context
 */
public static void generateKey(Context context) throws Exception {
    KeyStore keyStore;
    keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null, null);

    // Generate the RSA key pairs for encryption
    if (!keyStore.containsAlias(KEY_ALIAS)) {
        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(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
        kpg.initialize(spec);
        kpg.generateKeyPair();
    }
}
 
Example #2
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnNoSuchProviderExceptionWhenTryingToObtainRSAKeys() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);
    exception.expect(IncompatibleDeviceException.class);
    exception.expectMessage("The device is not compatible with the CryptoUtil class");

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    PowerMockito.mockStatic(KeyPairGenerator.class);
    PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE))
            .thenThrow(new NoSuchProviderException());

    cryptoUtil.getRSAKeyEntry();
}
 
Example #3
Source File: RsaAesCryptoManager.java    From pandroid with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
protected void initializeKeystore() throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    // Create new key if needed
    if (!keyStore.containsAlias(keyAlias)) {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 1);
        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keyAlias)
                .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                .setSerialNumber(BigInteger.ONE)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEYPAIR_ALGO, ANDROID_KEY_STORE);
        generator.initialize(spec);
        generator.generateKeyPair();
    }
}
 
Example #4
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Test
public void shouldThrowOnNoSuchAlgorithmExceptionWhenTryingToObtainRSAKeys() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);
    exception.expect(IncompatibleDeviceException.class);
    exception.expectMessage("The device is not compatible with the CryptoUtil class");

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    PowerMockito.mockStatic(KeyPairGenerator.class);
    PowerMockito.when(KeyPairGenerator.getInstance(ALGORITHM_RSA, ANDROID_KEY_STORE))
            .thenThrow(new NoSuchAlgorithmException());

    cryptoUtil.getRSAKeyEntry();
}
 
Example #5
Source File: Encryption.java    From dtube-mobile-unofficial with Apache License 2.0 6 votes vote down vote up
private void createNewKeys(String alias, KeyStore keyStore) {
    try {
        // Create new key if needed
        if (!keyStore.containsAlias(alias)) {
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 1);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(c.getApplicationContext())
                    .setAlias(alias)
                    .setSubject(new X500Principal("CN=Michael Kern (immawake), O=powerpoint45"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            KeyPair keyPair = generator.generateKeyPair();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #6
Source File: KeyStoreHelper.java    From xmrwallet with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void createKeysJBMR2(Context context, String alias) throws NoSuchProviderException,
        NoSuchAlgorithmException, InvalidAlgorithmParameterException {

    Calendar start = new GregorianCalendar();
    Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 300);

    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=" + alias))
            .setSerialNumber(BigInteger.valueOf(Math.abs(alias.hashCode())))
            .setStartDate(start.getTime()).setEndDate(end.getTime())
            .build();
    // defaults to 2048 bit modulus
    KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance(
            SecurityConstants.TYPE_RSA,
            SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    kpGenerator.initialize(spec);
    KeyPair kp = kpGenerator.generateKeyPair();
    Timber.d("preM Keys created");
}
 
Example #7
Source File: CryptHelper.java    From UpdogFarmer with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void createKeys(Context context) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException {
    // Create a start and end time, for the validity range of the key pair that's about to be
    // generated.
    final Calendar start = new GregorianCalendar();
    final Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 25);

    final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(ALIAS)
            .setSubject(new X500Principal("CN=" + ALIAS))
            .setSerialNumber(BigInteger.valueOf(1337))
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();

    // Initialize a KeyPair generator using the the intended algorithm (in this example, RSA
    // and the KeyStore.  This example uses the AndroidKeyStore.
    final KeyPairGenerator generator = KeyPairGenerator.getInstance(TYPE_RSA, KEYSTORE);
    generator.initialize(spec);

    final KeyPair kp = generator.generateKeyPair();
    Log.i(TAG, "Public key is " + kp.getPublic().toString());
}
 
Example #8
Source File: KeystoreTool.java    From secure-storage-android with Apache License 2.0 6 votes vote down vote up
private static void generateKeyPairUnderMarshmallow(@NonNull Context context) throws SecureStorageException {
    try {
        if (isRTL(context)) {
            Locale.setDefault(Locale.US);
        }

        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 99);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS)
                .setSubject(new X500Principal(KEY_X500PRINCIPAL))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();

        KeyPairGenerator generator
                = KeyPairGenerator.getInstance(KEY_ENCRYPTION_ALGORITHM, KEY_KEYSTORE_NAME);
        generator.initialize(spec);
        generator.generateKeyPair();
    } catch (Exception e) {
        throw new SecureStorageException(e.getMessage(), e, KEYSTORE_EXCEPTION);
    }
}
 
Example #9
Source File: PreAndroidMSecureKeyStore.java    From android-showcase-template with Apache License 2.0 6 votes vote down vote up
@Override
public void generatePrivateKeyPair(String keyAlias) throws GeneralSecurityException, IOException {
    //pre android-M, the keystore only support RSA key generation. So here we will generate a RSA keypair first, then generate the AES key.
    //we then encrypt the AES key using the generated RSA public key, and save it using the SharedPreferences
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 99);
    KeyPairGeneratorSpec generatorSpec = new KeyPairGeneratorSpec
            .Builder(context)
            .setAlias(keyAlias)
            .setSubject(new X500Principal("CN=" + keyAlias))
            .setSerialNumber(BigInteger.TEN)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE);
    generator.initialize(generatorSpec);
    generator.generateKeyPair();
}
 
Example #10
Source File: KeyStoreCipher.java    From adamant-android with GNU General Public License v3.0 6 votes vote down vote up
private void initGeneratorWithKeyPairGeneratorSpec(KeyPairGenerator generator, String alias) throws InvalidAlgorithmParameterException {
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, 200);

    KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec
            .Builder(context)
            .setAlias(alias)
            .setKeySize(KEY_SIZE)
            .setSerialNumber(BigInteger.ONE)
            .setSubject(new X500Principal("CN=" + alias + " CA Certificate"))
            .setStartDate(startDate.getTime())
            .setEndDate(endDate.getTime());

    generator.initialize(builder.build());
}
 
Example #11
Source File: SyncCryptoApi18Impl.java    From realm-android-user-store with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public void create_key_if_not_available() throws KeyStoreException {
    try {
        if (!keyStore.containsAlias(alias)) {
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 10);

            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(alias)
                    .setSubject(new X500Principal(X500_PRINCIPAL))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA",
                    "AndroidKeyStore");
            generator.initialize(spec);
            generator.generateKeyPair();
        }
    } catch (Exception e) {
        throw new KeyStoreException(e);
    }
}
 
Example #12
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeysForAPILessThanM(String keyAlias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableEntryException, NoSuchPaddingException, KeyStoreException, InvalidKeyException, IOException {
    // Generate a key pair for encryption
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
            .setAlias(keyAlias)
            .setSubject(new X500Principal("CN=" + keyAlias))
            .setSerialNumber(BigInteger.TEN)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM_NAME, ANDROID_KEY_STORE_NAME);
    kpg.initialize(spec);
    kpg.generateKeyPair();

    saveEncryptedKey();
}
 
Example #13
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private void generateOldKeyPair() throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
        // Generate the RSA key pairs
        if (!keyStore.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(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", AndroidKeyStore);
            kpg.initialize(spec);
            kpg.generateKeyPair();
        }
    }
 
Example #14
Source File: SecretKeyWrapper.java    From otp-authenticator with MIT License 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private static void generateKeyPair(Context context, String alias)
        throws GeneralSecurityException {
    final Calendar start = new GregorianCalendar();
    final Calendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 100);

    final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=" + alias))
            .setSerialNumber(BigInteger.ONE)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();

    final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

    gen.initialize(spec);
    gen.generateKeyPair();
}
 
Example #15
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
private KeyPairGeneratorSpec.Builder newKeyPairGeneratorSpecBuilder(KeyPairGeneratorSpec expectedBuilderOutput) {
    KeyPairGeneratorSpec.Builder builder = PowerMockito.mock(KeyPairGeneratorSpec.Builder.class);
    PowerMockito.when(builder.setAlias(anyString())).thenReturn(builder);
    PowerMockito.when(builder.setSubject(any(X500Principal.class))).thenReturn(builder);
    PowerMockito.when(builder.setKeySize(anyInt())).thenReturn(builder);
    PowerMockito.when(builder.setSerialNumber(any(BigInteger.class))).thenReturn(builder);
    PowerMockito.when(builder.setStartDate(any(Date.class))).thenReturn(builder);
    PowerMockito.when(builder.setEndDate(any(Date.class))).thenReturn(builder);
    PowerMockito.when(builder.setEncryptionRequired()).thenReturn(builder);
    PowerMockito.when(builder.build()).thenReturn(expectedBuilderOutput);
    return builder;
}
 
Example #16
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldThrowOnInvalidAlgorithmParameterExceptionWhenTryingToObtainRSAKeys() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);
    exception.expect(IncompatibleDeviceException.class);
    exception.expectMessage("The device is not compatible with the CryptoUtil class");

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    doThrow(new InvalidAlgorithmParameterException()).when(keyPairGenerator).initialize(any(AlgorithmParameterSpec.class));

    cryptoUtil.getRSAKeyEntry();
}
 
Example #17
Source File: AbstractAndroidKeystoreSecretKeyWrapper.java    From Android-Vault with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
private AlgorithmParameterSpec buildLegacyAlgorithmParameterSpec(Context context, String alias, Calendar start, Calendar end, BigInteger serialNumber, X500Principal subject) {
    return new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(subject)
            .setSerialNumber(serialNumber)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
}
 
Example #18
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 5 votes vote down vote up
private boolean generateKeyOld(
        Context context,
        String keystoreAlias,
        boolean isAuthenticationRequired
) {
    try {
        final Calendar start = Calendar.getInstance();
        final Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 25);

        final KeyPairGenerator keyGen = KeyPairGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");

        final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keystoreAlias)
                .setSubject(new X500Principal("CN=" + keystoreAlias))
                .setSerialNumber(BigInteger.valueOf(Math.abs(keystoreAlias.hashCode())))
                .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();
        return true;

    } catch ( NoSuchAlgorithmException
            | NoSuchProviderException
            | InvalidAlgorithmParameterException exc) {
        exc.printStackTrace();
        return false;
    }
}
 
Example #19
Source File: RNSecureKeyStoreModule.java    From react-native-secure-key-store with ISC License 5 votes vote down vote up
private PublicKey getOrCreatePublicKey(String alias) throws GeneralSecurityException, IOException {
  Locale currentLocale = Locale.getDefault();
  Locale.setDefault(Locale.ENGLISH);
  KeyStore keyStore = KeyStore.getInstance(getKeyStore());
  keyStore.load(null);

  if (!keyStore.containsAlias(alias) || keyStore.getCertificate(alias) == null) {
    Log.i(Constants.TAG, "no existing asymmetric keys for alias");

    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 50);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(getContext())
        .setAlias(alias)
        .setSubject(new X500Principal("CN=" + alias))
        .setSerialNumber(BigInteger.ONE)
        .setStartDate(start.getTime())
        .setEndDate(end.getTime())
        .build();

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", getKeyStore());
    generator.initialize(spec);
    generator.generateKeyPair();

    Locale.setDefault(currentLocale);
    Log.i(Constants.TAG, "created new asymmetric keys for alias");
  }

  return keyStore.getCertificate(alias).getPublicKey();
}
 
Example #20
Source File: EncryptionManagerAPI18.java    From samples-android with Apache License 2.0 5 votes vote down vote up
@Override
boolean generateKeyPair(Context context, KeyPairGenerator generator, String keyAlias,
                        int keySize, String encryptionPadding, String blockMode,
                        boolean isStrongBoxBacked, @Nullable byte[] seed) {
    Calendar startDate = Calendar.getInstance();
    //probable fix for the timezone issue
    startDate.add(Calendar.HOUR_OF_DAY, RSA_CALENDAR_HOURS_OFFSET);
    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.YEAR, RSA_CALENDAR_MAX_YEARS);

    try {
        KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(keyAlias)
                .setSerialNumber(BigInteger.ONE)
                .setSubject(new X500Principal(
                        "CN = Secured Preference Store, O = Devliving Online"))
                .setStartDate(startDate.getTime())
                .setEndDate(endDate.getTime());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            builder.setKeySize(keySize);
        }
        if (seed != null && seed.length > 0) {
            SecureRandom random = new SecureRandom(seed);
            generator.initialize(builder.build(), random);
        } else {
            generator.initialize(builder.build());
        }

        return true;
    } catch (InvalidAlgorithmParameterException e) {
        Log.e(TAG, "initialize KeyPairGenerator: ", e);
    }
    return false;
}
 
Example #21
Source File: CipherStorageSharedPreferencesKeystore.java    From keystore-ultimate with Apache License 2.0 5 votes vote down vote up
private AlgorithmParameterSpec getParameterSpec(String alias)  {
    GregorianCalendar start = new GregorianCalendar();
    GregorianCalendar end = new GregorianCalendar();
    end.add(Calendar.YEAR, 5);

    return new KeyPairGeneratorSpec.Builder(context)
            .setAlias(alias)
            .setSubject(new X500Principal("CN=" + alias))
            .setSerialNumber(KEY_SERIAL_NUMBER)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
}
 
Example #22
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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.JELLY_BEAN_MR2)
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 #23
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Test
@Config(sdk = 21)
public void shouldCreateUnprotectedRSAKeyPairIfMissingAndLockScreenDisabledOnAPI21() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyStore.PrivateKeyEntry expectedEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(expectedEntry);

    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    ArgumentCaptor<X500Principal> principalCaptor = ArgumentCaptor.forClass(X500Principal.class);
    ArgumentCaptor<Date> startDateCaptor = ArgumentCaptor.forClass(Date.class);
    ArgumentCaptor<Date> endDateCaptor = ArgumentCaptor.forClass(Date.class);

    //Set LockScreen as Disabled
    KeyguardManager kService = PowerMockito.mock(KeyguardManager.class);
    PowerMockito.when(context.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    PowerMockito.when(kService.isKeyguardSecure()).thenReturn(false);
    PowerMockito.when(kService.createConfirmDeviceCredentialIntent(any(CharSequence.class), any(CharSequence.class))).thenReturn(null);

    final KeyStore.PrivateKeyEntry entry = cryptoUtil.getRSAKeyEntry();

    Mockito.verify(builder).setKeySize(2048);
    Mockito.verify(builder).setSubject(principalCaptor.capture());
    Mockito.verify(builder).setAlias(KEY_ALIAS);
    Mockito.verify(builder).setSerialNumber(BigInteger.ONE);
    Mockito.verify(builder).setStartDate(startDateCaptor.capture());
    Mockito.verify(builder).setEndDate(endDateCaptor.capture());
    Mockito.verify(builder, never()).setEncryptionRequired();
    Mockito.verify(keyPairGenerator).initialize(spec);
    Mockito.verify(keyPairGenerator).generateKeyPair();

    assertThat(principalCaptor.getValue(), is(notNullValue()));
    assertThat(principalCaptor.getValue().getName(), is(CERTIFICATE_PRINCIPAL));

    assertThat(startDateCaptor.getValue(), is(notNullValue()));
    long diffMillis = startDateCaptor.getValue().getTime() - new Date().getTime();
    long days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(0L)); //Date is Today

    assertThat(endDateCaptor.getValue(), is(notNullValue()));
    diffMillis = endDateCaptor.getValue().getTime() - new Date().getTime();
    days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(greaterThan(25 * 365L))); //Date more than 25 Years in days

    assertThat(entry, is(expectedEntry));
}
 
Example #24
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Test
@Config(sdk = 21)
public void shouldCreateProtectedRSAKeyPairIfMissingAndLockScreenEnabledOnAPI21() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 21);

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyStore.PrivateKeyEntry expectedEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(expectedEntry);

    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    ArgumentCaptor<X500Principal> principalCaptor = ArgumentCaptor.forClass(X500Principal.class);
    ArgumentCaptor<Date> startDateCaptor = ArgumentCaptor.forClass(Date.class);
    ArgumentCaptor<Date> endDateCaptor = ArgumentCaptor.forClass(Date.class);

    //Set LockScreen as Enabled
    KeyguardManager kService = PowerMockito.mock(KeyguardManager.class);
    PowerMockito.when(context.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    PowerMockito.when(kService.isKeyguardSecure()).thenReturn(true);
    PowerMockito.when(kService.createConfirmDeviceCredentialIntent(any(CharSequence.class), any(CharSequence.class))).thenReturn(new Intent());

    final KeyStore.PrivateKeyEntry entry = cryptoUtil.getRSAKeyEntry();

    Mockito.verify(builder).setKeySize(2048);
    Mockito.verify(builder).setSubject(principalCaptor.capture());
    Mockito.verify(builder).setAlias(KEY_ALIAS);
    Mockito.verify(builder).setSerialNumber(BigInteger.ONE);
    Mockito.verify(builder).setStartDate(startDateCaptor.capture());
    Mockito.verify(builder).setEndDate(endDateCaptor.capture());
    Mockito.verify(builder).setEncryptionRequired();
    Mockito.verify(keyPairGenerator).initialize(spec);
    Mockito.verify(keyPairGenerator).generateKeyPair();

    assertThat(principalCaptor.getValue(), is(notNullValue()));
    assertThat(principalCaptor.getValue().getName(), is(CERTIFICATE_PRINCIPAL));

    assertThat(startDateCaptor.getValue(), is(notNullValue()));
    long diffMillis = startDateCaptor.getValue().getTime() - new Date().getTime();
    long days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(0L)); //Date is Today

    assertThat(endDateCaptor.getValue(), is(notNullValue()));
    diffMillis = endDateCaptor.getValue().getTime() - new Date().getTime();
    days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(greaterThan(25 * 365L))); //Date more than 25 Years in days

    assertThat(entry, is(expectedEntry));
}
 
Example #25
Source File: CryptoUtilTest.java    From Auth0.Android with MIT License 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Test
@Config(sdk = 19)
public void shouldNotCreateProtectedRSAKeyPairIfMissingAndLockScreenEnabledOnAPI19() throws Exception {
    ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 19);

    PowerMockito.when(keyStore.containsAlias(KEY_ALIAS)).thenReturn(false);
    KeyStore.PrivateKeyEntry expectedEntry = PowerMockito.mock(KeyStore.PrivateKeyEntry.class);
    PowerMockito.when(keyStore.getEntry(KEY_ALIAS, null)).thenReturn(expectedEntry);

    KeyPairGeneratorSpec spec = PowerMockito.mock(KeyPairGeneratorSpec.class);
    KeyPairGeneratorSpec.Builder builder = newKeyPairGeneratorSpecBuilder(spec);
    PowerMockito.whenNew(KeyPairGeneratorSpec.Builder.class).withAnyArguments().thenReturn(builder);

    ArgumentCaptor<X500Principal> principalCaptor = ArgumentCaptor.forClass(X500Principal.class);
    ArgumentCaptor<Date> startDateCaptor = ArgumentCaptor.forClass(Date.class);
    ArgumentCaptor<Date> endDateCaptor = ArgumentCaptor.forClass(Date.class);

    //Set LockScreen as Enabled
    KeyguardManager kService = PowerMockito.mock(KeyguardManager.class);
    PowerMockito.when(context.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(kService);
    PowerMockito.when(kService.isKeyguardSecure()).thenReturn(true);

    final KeyStore.PrivateKeyEntry entry = cryptoUtil.getRSAKeyEntry();

    Mockito.verify(builder).setKeySize(2048);
    Mockito.verify(builder).setSubject(principalCaptor.capture());
    Mockito.verify(builder).setAlias(KEY_ALIAS);
    Mockito.verify(builder).setSerialNumber(BigInteger.ONE);
    Mockito.verify(builder).setStartDate(startDateCaptor.capture());
    Mockito.verify(builder).setEndDate(endDateCaptor.capture());
    Mockito.verify(builder, never()).setEncryptionRequired();
    Mockito.verify(keyPairGenerator).initialize(spec);
    Mockito.verify(keyPairGenerator).generateKeyPair();

    assertThat(principalCaptor.getValue(), is(notNullValue()));
    assertThat(principalCaptor.getValue().getName(), is(CERTIFICATE_PRINCIPAL));

    assertThat(startDateCaptor.getValue(), is(notNullValue()));
    long diffMillis = startDateCaptor.getValue().getTime() - new Date().getTime();
    long days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(0L)); //Date is Today

    assertThat(endDateCaptor.getValue(), is(notNullValue()));
    diffMillis = endDateCaptor.getValue().getTime() - new Date().getTime();
    days = TimeUnit.MILLISECONDS.toDays(diffMillis);
    assertThat(days, is(greaterThan(25 * 365L))); //Date more than 25 Years in days

    assertThat(entry, is(expectedEntry));
}
 
Example #26
Source File: KeyStoreHelper.java    From andOTP with MIT License 4 votes vote down vote up
public static KeyPair loadOrGenerateAsymmetricKeyPair(Context context, String alias)
        throws GeneralSecurityException, IOException {
    final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);

    if (! keyStore.containsAlias(alias)) {
        final Calendar start = new GregorianCalendar();
        final Calendar end = new GregorianCalendar();
        end.add(Calendar.YEAR, 100);

        AlgorithmParameterSpec spec;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setCertificateSubject(new X500Principal("CN=" + alias))
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                    .setCertificateSerialNumber(BigInteger.ONE)
                    .setCertificateNotBefore(start.getTime())
                    .setCertificateNotAfter(end.getTime())
                    .build();
        } else {
            spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(alias)
                    .setSubject(new X500Principal("CN=" + alias))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
        }

        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");

        gen.initialize(spec);
        gen.generateKeyPair();
    }

    final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);

    if (entry != null)
        return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
    else
        return null;
}
 
Example #27
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 4 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
    public KeyStoreUtils() {
        GuardaApp.getAppComponent().inject(this);

        try {
            keyStore = KeyStore.getInstance(AndroidKeyStore);
            keyStore.load(null);

            if (!keyStore.containsAlias(KEY_ALIAS)) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
                    keyGenerator.init(
                            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                                    .setRandomizedEncryptionRequired(false)
                                    .build());
                    keyGenerator.generateKey();
                } else {
                    // 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(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
                    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", AndroidKeyStore);
                    kpg.initialize(spec);
                    kpg.generateKeyPair();
                }
            }

            //Generate and Store AES
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                generateAndStoreAES();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example #28
Source File: QlassifiedKeyStore.java    From Qlassified-Android with MIT License 4 votes vote down vote up
/**
 * 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.
 */
private void createKeys() throws
        NoSuchProviderException,
        NoSuchAlgorithmException,
        InvalidAlgorithmParameterException,
        InvalidKeyException {

    String alias = getUniqueDeviceId(this.context);
    KeyPairGenerator keyPairGenerator;

    /**
     * On Android Marshmellow we can use new security features
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        keyPairGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEYSTORE_INSTANCE);

        keyPairGenerator.initialize(
                new KeyGenParameterSpec.Builder(
                        alias,
                        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                        .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4))
                        .build());
    /**
     * On versions below Marshmellow but above Jelly Bean, use the next best thing
     */
    } else {

        Calendar start = new GregorianCalendar();
        Calendar end = new GregorianCalendar();
        end.add(Calendar.ERA, 1);

        KeyPairGeneratorSpec keyPairGeneratorSpec =
                new KeyPairGeneratorSpec.Builder(context)
                        // You'll use the alias later to retrieve the key.  It's a key for the key!
                        .setAlias(alias)
                                // The subject used for the self-signed certificate of the generated pair
                        .setSubject(new X500Principal("CN=" + alias))
                                // The serial number used for the self-signed certificate of the
                                // generated pair.
                        .setSerialNumber(BigInteger.valueOf(1337))
                        .setStartDate(start.getTime())
                        .setEndDate(end.getTime())
                        .build();

        keyPairGenerator = KeyPairGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEYSTORE_INSTANCE);
        keyPairGenerator.initialize(keyPairGeneratorSpec);
    /**
     * On versions below that...
     * Well we're sorry but you don't get a fancy encryption baby...
     */
    }

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Log.d("KeyStore", String.format("Public key: %s", keyPair.getPublic()));
    Log.d("KeyStore", String.format("Private key: %s", keyPair.getPrivate()));
}
 
Example #29
Source File: BasicAndroidKeyStoreFragment.java    From android-BasicAndroidKeyStore with Apache License 2.0 4 votes vote down vote up
/**
 * 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)
                // You'll use the alias later to retrieve the key.  It's a key for the key!
                .setAlias(mAlias)
                // The subject used for the self-signed certificate of the generated pair
                .setSubject(new X500Principal("CN=" + mAlias))
                // The serial number used for the self-signed certificate of the
                // generated pair.
                .setSerialNumber(BigInteger.valueOf(1337))
                // Date range of validity for the generated pair.
                .setStartDate(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 #30
Source File: KeyStoreHelper.java    From androidkeystore with Apache License 2.0 4 votes vote down vote up
/**
 * 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 {

	// 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(1, Calendar.YEAR);

	// The KeyPairGeneratorSpec object is how parameters for your key pair
	// are passed
	// to the KeyPairGenerator. For a fun home game, count how many classes
	// in this sample
	// start with the phrase "KeyPair".
	KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
			// You'll use the alias later to retrieve the key. It's a key
			// for the key!
			.setAlias(mAlias)
			// The subject used for the self-signed certificate of the
			// generated pair
			.setSubject(new X500Principal("CN=" + mAlias))
			// The serial number used for the self-signed certificate of the
			// generated pair.
			.setSerialNumber(BigInteger.valueOf(1337))
			// Date range of validity for the generated pair.
			.setStartDate(start.getTime()).setEndDate(end.getTime())
			.build();

	// 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);
	kpGenerator.initialize(spec);
	KeyPair kp = kpGenerator.generateKeyPair();
	Log.d(TAG, "Public Key is: " + kp.getPublic().toString());

}