Android Keymaster 是一種用于生成和管理設備上加密密鑰的 API
KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(
KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setUserAuthenticationRequired(true)
.set輪換周期(KEY_ROTATION_PERIOD) // 密鑰輪換周期,單位為天
.build();
KeymasterManager keymasterManager = (KeymasterManager) getSystemService(Context.KEYMASTER_SERVICE);
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
keyGenerator.init(keyGenParameterSpec);
KeyPair keyPair = keyGenerator.generateKeyPair();
// 獲取當前日期
Calendar calendar = Calendar.getInstance();
long currentTime = calendar.getTimeInMillis();
// 計算密鑰輪換的時間點
calendar.add(Calendar.DAY_OF_YEAR, KEY_ROTATION_PERIOD);
long rotationTime = calendar.getTimeInMillis();
// 刪除舊密鑰
try {
keymasterManager.deleteKey(KEY_NAME);
} catch (NoSuchAlgorithmException | InvalidKeyStoreException e) {
e.printStackTrace();
}
// 生成新的密鑰對
keyGenParameterSpec = new KeyGenParameterSpec.Builder(
KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
.setUserAuthenticationRequired(true)
.set輪換周期(KEY_ROTATION_PERIOD) // 密鑰輪換周期,單位為天
.build();
keyGenerator.init(keyGenParameterSpec);
keyPair = keyGenerator.generateKeyPair();
這樣,密鑰輪換策略就會根據您在步驟1中設置的輪換周期自動執行。請注意,這里的示例代碼僅適用于 RSA 密鑰對。如果您需要處理其他類型的密鑰(如對稱密鑰),請相應地調整代碼。