an example as follows:
 
import java.security.*;
import java.security.cert.*;
import java.io.*;public class getClientPrivateKey {
  static PrivateKey getPK(String p12, String u, String p)
throws
CertificateException,
IOException,
KeyStoreException,
NoSuchAlgorithmException,
UnrecoverableKeyException {
String keystorefile = p12;
String keyalias = u;
String keypasswd = p;
KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream fin = new FileInputStream(keystorefile);
ks.load(fin, keypasswd.toCharArray());
PrivateKey prikey =
 (PrivateKey) ks.getKey(keyalias, keypasswd.toCharArray());
java.security.cert.Certificate cert = 
                    ks.getCertificate(keyalias);
//PublicKey pubkey = cert.getPublicKey();
return prikey; }
}  I think it is what you want, enjoy!

解决方案 »

  1.   

    yeah
    c写起来就比较麻烦了
      

  2.   

    谢谢jffeng,我也是这么写的。其在load时打印一个“unknow attr1.17......"信息,然后就抛出异常。
      我用keytool去显示证书信息,其同样打印此出错信息,不过其能显示证书的信息,其显示证书格式未pkcs12,提供者为SunJSSE。
      我的证书不是keytool生成的,是从一家CA处申请的,他给安装在IE浏览器中,我把他导出,即为pfx后缀的文件。
      

  3.   

    对了,我的pfx文件由于是导出的,不知道别名,我用keystore的alias()方法取出是个很长的数字串,用这个别名去取也会抛出异常
      

  4.   

    unknown attr1.3.6.1.4.1.311.17.1
    6e0e93b2d73938affcec306c64fd4c04_ea9088c0-c4be-425b-97ea-8a4c282a6fdd
      

  5.   

    呵呵,你申请的CA肯定是使用M$的CA(换句话说是2000的系统产生的),在jdk1.3,或者1.42好像不能解决这个问题。要解决这个问题的办法,请看下面这一段。
    其实就是证书里面多了一段属性值,不是标准的。
    Attribute "1.3.6.1.4.1.311.17.1" is a Microsoft PKCS12 attribute.
    It contains the CSP name "Microsoft Base Cryptographic Provider..".PKCS12 files contain sequence of SafeBags along with pkcs12 attributes,
    such as friendlyName, localKeyId, which are optional. Our PKCS12
    implementation recognizes these attributes, as per the PKCS12 spec.
    However, if pkcs12 file contains any other unknown attributes (such as
    Microsoft pkcs12 attribute), we skip it, and continue to parse the
    pkcs12 file.Hence, you should be able to read the pkcs12 correctly. When using J2SE
    1.4.2
    to read pkcs12 file, it will merely display the attributes that we do
    not recognize.
    Hence the message "unknown attr1.3.6.1.4.1.311.17.1". In J2SE 1.5.0, we
    no longer
    display the unknown attributes.If you want to suppress this message using J2SE 1.4.2, you could flush this
    pkcs12 file through Netscape/OpenSSL and this attribute will no longer
    exist.
      

  6.   

    你再看这:http://support.microsoft.com/default.aspx?scid=kb;en-us;Q287547
    Microsoft PKCS12 attributes.....................1.3.6.1.4.1.311.17
            szOID_LOCAL_MACHINE_KEYSET              1.3.6.1.4.1.311.17.1
    上次认不出来这个属性哟。:)