導入Java . io . *;
導入Java . util . *;
導入Java . security . *;
導入Java . security . cert . certificate;
公共類ReadPFX {
public ReadPFX (){
}
//轉換為十六進制字符串
公共靜態字符串Byte2String(byte[] b) {
字符串hs =
字符串stmp =
for(int n = 0;n & ltb .長度;n++) {
stmp =(Java . lang . integer . tohexstring(b[n]& amp;0x ff));
if(stmp . length()= = 1)hs = hs+" 0 "+stmp;
else hs = hs+stmp;
//if(n & lt;b . length-1)hs = hs+":";
}
返回hs . toupper case();
}
公共靜態字節[]字符串字節(整數){
int temp = number
byte[]b =新字節[4];
for(int I = b . length-1;我& gt-1;我- ){
b[i] =新整數(temp & amp0xff)。byte value();//將最高位保存在最低位。
temp = temp & gt& gt8;//向右移動8位
}
返回b;
}
private key GetPvkformPfx(String strPfx,String strPassword){
嘗試{
KeyStore ks = KeyStore . getinstance(" pkcs 12 ");
file inputstream fis = new file inputstream(strPfx);
//如果密鑰庫密碼為空(""),那麽我們必須設置
//到null,否則不行!!!
char[]n password = null;
if((str password = = null)| | str password . trim()。等於(" "){
nPassword = null
}
其他
{
nPassword = str password . tochararray();
}
ks.load(fis,nPassword);
fis . close();
system . out . println(" keystore type = "+ks . gettype());
//現在我們循環所有的別名,我們需要別名來獲取密鑰。
//該值似乎是中的“友好名稱”字段
//details tab & lt;-證書窗口& lt-查看& lt-證書
//Button & lt;-內容選項卡& lt-互聯網選項<。-工具菜單
//在MS IE 6中。
enumeration enumas = ks . aliases();
String keyAlias = null
if (enumas.hasMoreElements())//我們只讀取壹個證書。
{
key alias =(String)enumas . nextelement();
system . out . println(" alias =["+keyAlias+"]");
}
//現在壹旦我們知道了別名,我們就可以得到鑰匙。
system . out . println(" is key entry = "+ks . iskey entry(keyAlias));
private key prikey =(private key)ks . getkey(keyAlias,nPassword);
certificate cert = ks . get certificate(keyAlias);
public key pubkey = cert . get public key();
system . out . println(" cert class = "+cert . getclass()。getName());
system . out . println(" cert = "+cert);
system . out . println(" public key = "+pubkey ");
System.out.println("私鑰= "+prikey ");
返回prikey
}
捕捉(例外e)
{
e . printstacktrace();
}
返回null
}
}