Android凭据加密存储区如何使用,java代码示例
时间: 2023-05-30 09:01:30 浏览: 164
Android凭据加密存储区(Credential encrypted storage area)是一种安全存储凭据(如密码、令牌、证书等)的方式,可以保护敏感数据不被恶意应用或攻击者窃取。在使用Credential encrypted storage area时,需要创建一个Key,用于加密和解密数据。以下是一个简单的Java代码示例,演示如何使用Credential encrypted storage area:
1. 创建一个Key
```
Key key = null;
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
if (keyguardManager.isKeyguardSecure()) {
// Create the keys for Credential Encrypted Storage Area
KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
"myKeyAlias",
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setUserAuthenticationRequired(true)
.setUserAuthenticationValidityDurationSeconds(30);
KeyGenerator keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
keyGenerator.init(builder.build());
key = keyGenerator.generateKey();
}
```
2. 存储数据
```
String dataToStore = "my password";
byte[] encryptedData = null;
try {
// Get the Cipher
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
// Encrypt the data
encryptedData = cipher.doFinal(dataToStore.getBytes());
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
if (encryptedData != null) {
// Store the encrypted data in the SharedPreferences
SharedPreferences.Editor editor = getSharedPreferences("myPrefs", MODE_PRIVATE).edit();
editor.putString("myEncryptedData", Base64.encodeToString(encryptedData, Base64.DEFAULT));
editor.apply();
}
```
3. 读取数据
```
String encryptedDataString = getSharedPreferences("myPrefs", MODE_PRIVATE)
.getString("myEncryptedData", null);
if (encryptedDataString != null) {
byte[] encryptedData = Base64.decode(encryptedDataString, Base64.DEFAULT);
try {
// Get the Cipher
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key);
// Decrypt the data
byte[] decryptedData = cipher.doFinal(encryptedData);
String data = new String(decryptedData);
Log.d(TAG, "Decrypted data: " + data);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
}
```
以上是一个简单的示例,更复杂的应用可能需要更多的代码来管理Key和加密/解密数据。同时,需要注意,Credential encrypted storage area只能在设备上启用了屏幕锁定并设置了密码、PIN码、图案等屏幕锁定方式时才能使用。
阅读全文