我正在使用Android M指纹API来允许用户登录该应用程序.为此,我需要在设备上存储用户名和密码.目前我有登录工作,以及指纹API,但用户名和密码都存储为纯文本.我想在存储之前加密密码,并且能够在用户使用指纹进行身份验证后检索密码.
我正在努力解决这个问题.我一直试图从Android安全样本中应用我能做的,但每个例子似乎只处理加密或签名,而不是解密.
到目前为止,我必须获得AndroidKeyStorea KeyPairGenerator和a 的实例Cipher,使用非对称加密技术来允许使用Android KeyGenParameterSpec.Builder().setUserAuthenticationRequired(true).非对称加密的原因是因为如果用户未经过身份验证,该setUserAuthenticationRequired方法将阻止对密钥的任何使用,但是:
此授权仅适用于密钥和私钥操作.公钥操作不受限制.
这应该允许我在用户使用其指纹进行身份验证之前使用公钥加密密码,然后仅在用户通过身份验证后使用私钥进行解密.
public KeyStore getKeyStore() {
try {
return KeyStore.getInstance("AndroidKeyStore");
} catch (KeyStoreException exception) {
throw new RuntimeException("Failed to get an instance of KeyStore", exception);
}
}
public KeyPairGenerator getKeyPairGenerator() {
try {
return KeyPairGenerator.getInstance("EC", "AndroidKeyStore");
} catch(NoSuchAlgorithmException | NoSuchProviderException exception) {
throw new RuntimeException("Failed to get an instance of KeyPairGenerator", exception);
}
}
public Cipher getCipher() {
try {
return …Run Code Online (Sandbox Code Playgroud) 我android.security.KeyStoreException: Unknown error在少数具有不同 Android 版本的设备上使用 (6 - 8)
这是我的密钥生成代码:
final KeyPairGenerator keyGenerator = KeyPairGenerator
.getInstance(KeyProperties.KEY_ALGORITHM_RSA,
ANDROID_KEY_STORE);
keyGenerator.initialize(new KeyGenParameterSpec.Builder(ALIAS,
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setKeySize(2048)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.build());
return keyGenerator.generateKeyPair();
Run Code Online (Sandbox Code Playgroud)
这就是我加载 keyPair 的方式:
if (keyStore.containsAlias(ALIAS))
{
KeyStore.Entry entry = keyStore.getEntry(ALIAS, null);
if (entry != null)
{
if (entry instanceof KeyStore.PrivateKeyEntry)
{
Log.i(TAG, "KeyPair found.");
KeyStore.PrivateKeyEntry pke = (KeyStore.PrivateKeyEntry) entry;
Certificate cert = pke.getCertificate();
if (cert != null)
{
return new KeyPair(cert.getPublicKey(), pke.getPrivateKey());
}
Log.w(TAG, "Cert / Public Key is null");
}
} …Run Code Online (Sandbox Code Playgroud)