您从 BasicAndroidKeyStore 指向的 example code 不会将公钥记录为 KeyPair 类中的 getPublic() 仅返回对公钥对象的引用,而不是公钥本身。
Log.d(TAG, "Public Key reference is: " + kp.getPublic().toString());
日志:
D/KeyStoreFragment:公钥参考为:android.security.keystore.AndroidKeyStoreRSAPublicKey@b8004e8f
getPrivate() 也是如此。
Log.d(TAG, "Private Key reference is: " + kp.getPrivate().toString());
日志:
D/KeyStoreFragment:私钥参考是
android.security.keystore.AndroidKeyStoreRSAPrivateKey@5da42c27
现在,正如您在评论中指出的那样,kp.getPublic().getEncoded() 将返回实际的公钥,但公钥的原始用途并不意味着保密。
私钥是保密的,当使用硬件支持的密钥库和设备的安全硬件支持的密钥时,密钥安全地存储在 TEE/SE 中,不能由应用程序本身或其他错误提取具有root权限的演员。你可以在这个例子中看到它:
Log.d(TAG, "Private Key is " + Arrays.toString(kp.getPrivate().getEncoded()));
日志:
D/KeyStoreFragment:私钥为空
要验证您的设备的安全硬件是否支持您的密钥,您可以使用此代码的一些变体来满足您的需求。您可以在示例应用的 createKeys() 方法中将这个 sn-p 粘贴到上面提到的 Log.d 之后。
KeyFactory factory = KeyFactory.getInstance(kp.getPrivate().getAlgorithm(), "AndroidKeyStore");
KeyInfo keyInfo = null;
try {
keyInfo = factory.getKeySpec(kp.getPrivate(), KeyInfo.class);
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
if (keyInfo.isInsideSecureHardware())
Log.d(TAG, "Key is supported in secure hardware");
else
Log.d(TAG, "Key is not supported in secure hardware");