在我的应用程序中,我以共享首选项保存一些数据,这些数据在保存前必须加密,在检索时必须解密。
我使用的是AES-256加密。为此,我使用密码短语/pin生成密钥。下面是我的代码片段。
public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
// Number of PBKDF2 hardening rounds to use. Larger values increase
// computation time. You should select a value that causes computation
// to take >100ms.
final int iterations = 1000;
// Generate a 256-bit key
final int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength);
SecretKey secretKey = secretKeyFactory.generateSecret(keySpec);
return secretKey;
}
根据我的应用程序,我可以要求用户提供一个唯一的pin。但我无法将pin保存在密钥库中,因为该应用程序必须从4.0开始支持。如何保存密码?
为此,我建议您考虑使用Facebook Conceal库。根据他们的build.gradle
,它与android兼容,最高可达API 9:https://github.com/facebook/conceal/blob/master/build.gradle
您可以在网站上遵循他们关于如何集成的指导:
https://github.com/facebook/conceal
请改用KeyChain。它与API 14(ICS)兼容。主要区别在于KeyChain在全系统范围内可用。
然而,我想知道,你为什么要把别针藏起来?存在受密码保护的密钥以防止未经授权的使用,因此用户应通过输入其密码来授权使用。