将Key对象转换为PrivateKey

时间:2014-09-24 19:06:14

标签: android keystore

我需要使用KeyStore类中的以下方法:

public Key getPrivateKey(String alias)

但最后我需要PrivateKey对象,而不是Key。如何将Key对象转换为PrivateKey? 谢谢!

2 个答案:

答案 0 :(得分:0)

从密钥库中键入密钥后 创建密钥对,然后从密钥对中获取pub和priv密钥,如下所示:

Key prvkey = keyStore.getKey(_alias,_keypass.toCharArray());
PublicKey pubkey = certificate.getPublicKey();
KeyPair keypair = new KeyPair(pubkey, (PrivateKey)prvkey);
PrivateKey privKewy = keypair.getPrivate();

答案 1 :(得分:0)

//get keystore 
//jks for type "JKS",
//.p12 or .pfx for type "PKCS12"
//specification name is PKCS#12, but the # is not used in the Java keystore type name
KeyStore keystore = KeyStore.getInstance("pkcs12");
//load keystore - is FileImputStream to location of your pfx/jks file          
keystore.load(is, password);
//get private key           
PrivateKey privateKey = (PrivateKey)keystore.getKey(alias, password);