本文整理匯總了Java中android.security.keystore.KeyGenParameterSpec.Builder方法的典型用法代碼示例。如果您正苦於以下問題:Java KeyGenParameterSpec.Builder方法的具體用法?Java KeyGenParameterSpec.Builder怎麽用?Java KeyGenParameterSpec.Builder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類android.security.keystore.KeyGenParameterSpec
的用法示例。
在下文中一共展示了KeyGenParameterSpec.Builder方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: generateKey
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
protected SecretKey generateKey() {
SecretKey key = null;
try {
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
getKeyAlias(),
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
KeyGenParameterSpec keySpec = builder
.setKeySize(CIPHER_KEY_LENGHT)
.setBlockModes(CIPHER_BLOCKS)
.setEncryptionPaddings(CIPHER_PADDING)
.setRandomizedEncryptionRequired(false) //FIXME: set to true because we should be using IND-CPA but this means that a IV has to be store per token (less generic than i though)
.setUserAuthenticationRequired(isKeyPinRequired())
.setUserAuthenticationValidityDurationSeconds(getKeyPinDuration())
.build();
KeyGenerator kg = KeyGenerator.getInstance(CIPHER_ALGO, KEYSTORE_TYPE);
kg.init(keySpec);
key = kg.generateKey();
} catch (InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException e) {
Log.e(TAG, "Couldn't generate secret key", e);
}
return key;
}
示例2: getSecretKey
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
/**
* Gets a secret key from Android key store.
* If no key has been generated with a given alias then generate a new one
* @return
* @throws KeyStoreException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws NoSuchProviderException
* @throws InvalidAlgorithmParameterException
* @throws UnrecoverableKeyException
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private static Key getSecretKey() throws GeneralSecurityException, IOException {
KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
keyStore.load(null);
if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE_ANDROID);
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_ALIAS_AMAZE,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
builder.setBlockModes(KeyProperties.BLOCK_MODE_GCM);
builder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE);
builder.setRandomizedEncryptionRequired(false);
keyGenerator.init(builder.build());
return keyGenerator.generateKey();
} else {
return keyStore.getKey(KEY_ALIAS_AMAZE, null);
}
}
示例3: createKeyPair
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
@TargetApi(23)
public KeyPair createKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws CryptoException
{
KeyPair keyPair = null;
try {
KeyStore mKeyStore = KeyStore.getInstance(REST_AUTH_KEYSTORE_NAME);
mKeyStore.load(null);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC, REST_AUTH_KEYSTORE_NAME);
KeyGenParameterSpec.Builder builder
= new KeyGenParameterSpec.Builder(keyName,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT |
KeyProperties.PURPOSE_SIGN)
.setDigests(KeyProperties.DIGEST_SHA256)
.setAlgorithmParameterSpec(new ECGenParameterSpec(REST_AUTH_EC_CURVE))
.setUserAuthenticationRequired(true);
// This call is only available on API level >= 24.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
}
keyPairGenerator.initialize(builder.build());
keyPair = keyPairGenerator.generateKeyPair();
} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException |
InvalidAlgorithmParameterException | CertificateException | IOException e)
{
throw new CryptoException(e.getMessage());
}
return keyPair;
}
示例4: initKeyStore
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
/**
* Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the
* Android Keystore.
*/
private void initKeyStore() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
return;
}
try {
mKeyStore = KeyStore.getInstance(ANDROID_KEYSTORE_PROVIDER);
mKeyStore.load(null);
// Check if a generated key exists under the KEY_ALIAS_AES .
if (!mKeyStore.containsAlias(KEY_ALIAS_AES)) {
KeyGenerator keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);
KeyGenParameterSpec.Builder builder = null;
builder = new KeyGenParameterSpec.Builder(
KEY_ALIAS_AES,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setKeySize(256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
// forces user authentication with fingerprint
.setUserAuthenticationRequired(true);
keyGenerator.init(builder.build());
keyGenerator.generateKey();
}
} catch (Exception e) {
}
}
示例5: newKeyGenParameterSpecBuilder
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
@RequiresApi(api = Build.VERSION_CODES.M)
private KeyGenParameterSpec.Builder newKeyGenParameterSpecBuilder(KeyGenParameterSpec expectedBuilderOutput) {
KeyGenParameterSpec.Builder builder = PowerMockito.mock(KeyGenParameterSpec.Builder.class);
PowerMockito.when(builder.setKeySize(anyInt())).thenReturn(builder);
PowerMockito.when(builder.setCertificateSubject(any(X500Principal.class))).thenReturn(builder);
PowerMockito.when(builder.setCertificateSerialNumber(any(BigInteger.class))).thenReturn(builder);
PowerMockito.when(builder.setCertificateNotBefore(any(Date.class))).thenReturn(builder);
PowerMockito.when(builder.setCertificateNotAfter(any(Date.class))).thenReturn(builder);
//noinspection WrongConstant
PowerMockito.when(builder.setEncryptionPaddings(anyString())).thenReturn(builder);
//noinspection WrongConstant
PowerMockito.when(builder.setBlockModes(anyString())).thenReturn(builder);
PowerMockito.when(builder.build()).thenReturn(expectedBuilderOutput);
return builder;
}
示例6: getKeyGenParameterSpecBuilder
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
@NonNull
@TargetApi(Build.VERSION_CODES.M)
static KeyGenParameterSpec.Builder getKeyGenParameterSpecBuilder(String keyName, String blockModes, String encryptionPaddings, boolean invalidatedByBiometricEnrollment) {
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(blockModes)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(encryptionPaddings);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
}
return builder;
}
示例7: generateAesKey
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
/**
* Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the
* Android Keystore.
*/
@SuppressWarnings("StatementWithEmptyBody")
private void generateAesKey() {
try {
// The KeyGenerator is an engine class for creating symmetric keys utilizing the
// algorithm it was initialized with.
KeyGenerator keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);
// Create a new instance of the KeyGenParameterSpec.Builder, hand over
// the key alias and the different purposes for which you want to use the key.
// Keep in mind that you can only use the key for the operations you have specified
// here - once the key is created it can't be changed.
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
KEY_ALIAS_AES,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
// Define the basic encryption parameters for the key. The set configuration
// matches the AES_DEFAULT_TRANSFORMATION constant.
builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setKeySize(256)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
if (mRadioUserAuthentication.isChecked()) {
// Create a key which requires the user to be authenticated during
// the last 30 seconds. Could also be 30 seconds or even 5 minutes -
// choose whatever fits your security guidelines best.
// Before continuing, check if the user has set up a secure lockscreen -
// if not, prompt the user to set one up ;-)
if (!hasSetupSecureLockscreen()) return;
builder.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(15);
} else if (mRadioUserFingerprint.isChecked()) {
// Create a key which needs fingerprint authentication every time.
// Before continuing, check if the device supports fingerprint
// authentication and if the user has at least enrolled one fingerprint -
// if not, prompt the user to enroll one ;-)
if (!hasSetupFingerprint()) return;
builder.setUserAuthenticationRequired(true);
} else {
// Create a key which does not need any user authentication.
// Nothing more to add here!
}
// Initialize the KeyGenerator with the KeyGenParameterSpec which will be created by
// the KeyGenParameterSpec.Builder .
keyGenerator.init(builder.build());
// Finally, generate the key...
keyGenerator.generateKey();
// ...and show a TextView with a confirmation text.
showSuccessTextView();
} catch (NoSuchAlgorithmException | NoSuchProviderException
| InvalidAlgorithmParameterException e) {
throw new RuntimeException("Failed to create a symmetric key", e);
}
}
示例8: shouldCreateRSAKeyPairIfMissingOnAPI23AndUp
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
@RequiresApi(api = Build.VERSION_CODES.M)
@Test
@Config(constants = com.auth0.android.auth0.BuildConfig.class, sdk = 23, manifest = Config.NONE)
public void shouldCreateRSAKeyPairIfMissingOnAPI23AndUp() throws Exception {
ReflectionHelpers.setStaticField(Build.VERSION.class, "SDK_INT", 23);
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);
KeyGenParameterSpec spec = PowerMockito.mock(KeyGenParameterSpec.class);
KeyGenParameterSpec.Builder builder = newKeyGenParameterSpecBuilder(spec);
PowerMockito.whenNew(KeyGenParameterSpec.Builder.class).withArguments(KEY_ALIAS, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT).thenReturn(builder);
ArgumentCaptor<X500Principal> principalCaptor = ArgumentCaptor.forClass(X500Principal.class);
ArgumentCaptor<Date> startDateCaptor = ArgumentCaptor.forClass(Date.class);
ArgumentCaptor<Date> endDateCaptor = ArgumentCaptor.forClass(Date.class);
final KeyStore.PrivateKeyEntry entry = cryptoUtil.getRSAKeyEntry();
Mockito.verify(builder).setKeySize(2048);
Mockito.verify(builder).setCertificateSubject(principalCaptor.capture());
Mockito.verify(builder).setCertificateSerialNumber(BigInteger.ONE);
Mockito.verify(builder).setCertificateNotBefore(startDateCaptor.capture());
Mockito.verify(builder).setCertificateNotAfter(endDateCaptor.capture());
Mockito.verify(builder).setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1);
Mockito.verify(builder).setBlockModes(KeyProperties.BLOCK_MODE_ECB);
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));
}
示例9: generateKeyPair
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
@Override
public KeyPair generateKeyPair(String username) {
Log.d(TAG, "generateKeyPair");
try {
String keyId = getKeyId(username);
Log.d(TAG, "keyId = " + keyId);
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
keyId,
KeyProperties.PURPOSE_SIGN)
.setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
.setDigests(KeyProperties.DIGEST_SHA256,
KeyProperties.DIGEST_SHA384,
KeyProperties.DIGEST_SHA512)
// Only permit the private key to be used if the user authenticated
// within the last five minutes.
.setUserAuthenticationRequired(true);
if (!isFingerprintAuthAvailable()) {
// make sure key can be used with PIN if no FP available or supported
// authenticaton is done via the confirmCredentials() API
builder = builder.setUserAuthenticationValidityDurationSeconds(KEY_TIMEOUT_SECS);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// XXX this needs to be the real server challenge
builder = builder.setAttestationChallenge(new byte[16]);
builder = builder.setInvalidatedByBiometricEnrollment(false);
}
keyPairGenerator.initialize(builder.build());
KeyPair keyPair = keyPairGenerator.generateKeyPair();
Log.d(TAG, "Generated keypair : " + keyPair);
KeyStore keyStore = getAndroidKeyStore();
X509Certificate cert = (X509Certificate) keyStore.getCertificate(keyId);
Log.d(TAG, "certificate: " + cert);
return keyPair;
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
示例10: generateAESKey
import android.security.keystore.KeyGenParameterSpec; //導入方法依賴的package包/類
/**
* this method will generate a SecretKey and store it in the key store under the keystoreAlias.
* you need the keystoreAlias to get it the Secret key from keyStore
*
* @param keystoreAlias
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws InvalidAlgorithmParameterException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private SecretKey generateAESKey(String keystoreAlias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException, IOException, CertificateException {
fixPrng();
KeyGenerator keyGen = KeyGenerator.getInstance(AES.CIPHER, KeyStoreConstants.PROVIDER);
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keystoreAlias,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setKeySize(AES.KEY_LENGTH_BITS)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
keyGen.init(builder.build());
return keyGen.generateKey();
}