Java Code Examples for android.security.KeyPairGeneratorSpec#Builder

The following examples show how to use android.security.KeyPairGeneratorSpec#Builder . 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: 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 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: 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 4
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 5
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 6
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 7
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 8
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 9
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));
}