我正在尝试使用以下代码在Android的Secure元素中存储一小段文本:
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
PasswordProtection keyStorePP = new KeyStore.PasswordProtection(null);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEwithHmacSHA1");
SecretKey generatedSecret = factory.generateSecret(newPBEKeySpec(mySecureText.toCharArray()));
ks.setEntry("alias", new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP);
上面的代码提供了以下异常:
08-17 14:39:32.832: W/System.err(11713): java.security.KeyStoreException: Unsupported protection parameter class: java.security.KeyStore$PasswordProtection. Supported: android.security.keystore.KeyProtection
有什么我做错了或只是AndroidKeyStore不支持存储字符串?
最后,如果我切换到BKS,代码将会执行。
感谢。
答案 0 :(得分:0)
错误告诉您更改此内容:
PasswordProtection keyStorePP = new KeyStore.PasswordProtection(null);
到此
PasswordProtection keyStorePP = new KeyStore.KeyProtection();
答案 1 :(得分:0)
KeyProtection无法设置空密码。
char[] password = {'p','a','s','s'};
KeyStore.ProtectionParameter protParam =
new KeyStore.PasswordProtection(password);
ks.setEntry("alias", new KeyStore.SecretKeyEntry(generatedSecret), keyStorePP);
答案 2 :(得分:0)
我让它在下面工作。这是您指定新的KeyProtection的方式:
import android.security.keystore.KeyProtection;
import android.security.keystore.KeyProperties;
...............
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null, null);
SecureRandom secureRandom = new SecureRandom(mySecureText.getBytes());
KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES);
keyGenerator.init(256, secureRandom);
SecretKeySpec keySpec = new SecretKeySpec(keyGenerator.generateKey().getEncoded(), KeyProperties.KEY_ALGORITHM_AES);
keyStore.setEntry(alias, new SecretKeyEntry(keySpec),
new KeyProtection.Builder(KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setRandomizedEncryptionRequired(false)
.build()
);