我遇到了以下问题:
我需要创建一个KeyPair,在其中将其插入getEncoded()
之前,需要访问一次PrivateKey的AndroidKeyStore
。
通过AndroidKeyStore
生成密钥时,所得的密钥getEncoded()
方法将返回null
(作为一种额外的密钥保护机制)。
这是我使用KeyGenParameterSpec生成密钥的方式(仅针对Android.M以上的设备):
public AlgorithmParameterSpec createSpec(){
Calendar start = new GregorianCalendar();
Calendar end = new GregorianCalendar();
end.add(Calendar.YEAR, 1);
String alias = "myKeyAlias";
AlgorithmParameterSpec spec = new KeyGenParameterSpec.Builder(alias,
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY |
KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
.setCertificateSubject(new X500Principal("CN=" + alias))
.setDigests(KeyProperties.DIGEST_SHA256)
.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
.setCertificateSerialNumber(BigInteger.valueOf(1337))
.setCertificateNotBefore(start.getTime())
.setCertificateNotAfter(end.getTime())
.build();
return spec;
}
public KeyPair generateKeyPairInKeystore(AlgorithmParameterSpec spec){
KeyPairGenerator kpGenerator = KeyPairGenerator
.getInstance("RSA", "AndroidKeyStore");
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();
//here kp.getPrivate().getEncrypted() doesn't give me the key
return kp;
}
public KeyPair generateKeyPair(AlgorithmParameterSpec spec){
KeyPairGenerator kpGenerator = KeyPairGenerator
.getInstance(SecurityConstants.TYPE_RSA);
kpGenerator.initialize(spec);
KeyPair kp = kpGenerator.generateKeyPair();
//I cannot receive the encrypted Key here either
//kp.getPrivate().getEncrypted();
return kp;
}
这些密钥在AndroidKeyStore
内部生成,因此会自动存储在其中。但是我无法访问getEncrypted()
才能将其发送到受信任的服务器。
所以我想念的是:
PrivateKey
可以访问的地方创建getEncoded()
?KeyStore
中(需要提供证书)?