在
this blog之后,我使用此代码在Android KeyStore中创建和存储KeyPair:
Context ctx = getApplicationContext(); Calendar notBefore = Calendar.getInstance(); Calendar notAfter = Calendar.getInstance(); notAfter.add(1,Calendar.YEAR); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(ctx). setAlias(RSA_KEYS_ALIAS).setSubject( new X500Principal(String.format("CN=%s,OU=%s",getApplicationName(),ctx.getPackageName()))). setSerialNumber(BigInteger.ONE). setStartDate(notBefore.getTime()).setEndDate(notAfter.getTime()).build(); KeyPairGenerator kpGenerator; try { kpGenerator = KeyPairGenerator.getInstance("RSA","AndroidKeyStore"); kpGenerator.initialize(spec); kpGenerator.generateKeyPair(); } catch (Exception e) { showException(e); }
当我尝试使用此代码从KeyStore检索公钥时,抛出带有消息链== null的NullPointerException.
public RSAPublicKey getRSAPublicKey() { RSAPublicKey result = null; try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(RSA_KEYS_ALIAS,null); // --< exception is thrown here result = (RSAPublicKey) keyEntry.getCertificate().getPublicKey(); } } catch (Exception e) { showException(e); } return result; }
检索私钥的代码也是如此.
更新:
我将我的代码与Google BasicAndroidKeyStore sample进行了比较.在该示例中生成,存储和检索密钥对的机制几乎与我实现的相同.我很困惑为什么这段代码在经过几个月的完美工作后已停止运作.
任何建议或提示将不胜感激.
解决方法
显然,Android KeyStore中的名称在所有应用程序中必须是唯一的.我有另一个应用程序,它的键使用相同的名称.更改两个应用程序使用的公共库以创建和使用键在其键名中包含包名称后,问题就消失了……
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。