我试图使密钥库帮助我生成用于AES加密的密钥,并使用它来加密我输入的纯文本。所以这是我的代码。我在另一个活动的onCreate()方法中仅调用一次createKey()方法,然后使用相同的keyAlias和相同的纯文本多次调用printCipherText()方法。奇怪的是:每次我调用printCipherText()方法时,都会得到不同的结果。我使用相同的密钥别名和相同的明文,但是为什么每次都得到不同的密文?
public class KeyCreatorClass {
KeyStore keyStore;
KeyGenerator keyGenerator;
Cipher cipher;
public void createKey(String keyAlias) { //I call this method only once in the onCreate() method of another activity, with keyAlias "A"
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
keyStore.load(null);
keyGenerator.init(
new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(false)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.setRandomizedEncryptionRequired(false)
.build());
keyGenerator.generateKey();
} catch (Exception e) {
e.printStackTrace();
}
}
public String printCipherText(String keyAlias, String plainText){ //I call this method many times with the same …Run Code Online (Sandbox Code Playgroud)