Java从pfx中获取公私钥

本文提供了一个Java示例程序,演示如何从PFX文件中读取私钥。通过使用PKCS12标准,该程序能够加载密钥库,并获取证书及私钥等关键信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.Jinhill; import java.io.*; import java.util.*; import java.security.*; import java.security.cert.Certificate; public class ReadPFX { public ReadPFX (){ } //转换成十六进制字符串 public static String Byte2String(byte[] b) { String hs=""; String stmp=""; for (int n=0;n<b.length;n++) { stmp=(java.lang.Integer.toHexString(b[n] & 0XFF)); if (stmp.length()==1) hs=hs+"0"+stmp; else hs=hs+stmp; //if (n<b.length-1) hs=hs+":"; } return hs.toUpperCase(); } public static byte[] StringToByte(int number) { int temp = number; byte[] b=new byte[4]; for (int i=b.length-1;i>-1;i--){ b[i] = new Integer(temp&0xff).byteValue();//将最高位保存在最低位 temp = temp >> 8; //向右移8位 } return b; } private PrivateKey GetPvkformPfx(String strPfx, String strPassword){ try { KeyStore ks = KeyStore.getInstance("PKCS12"); FileInputStream fis = new FileInputStream(strPfx); // If the keystore password is empty(""), then we have to set // to null, otherwise it won't work!!! char[] nPassword = null; if ((strPassword == null) || strPassword.trim().equals("")){ nPassword = null; } else { nPassword = strPassword.toCharArray(); } ks.load(fis, nPassword); fis.close(); System.out.println("keystore type=" + ks.getType()); // Now we loop all the aliases, we need the alias to get keys. // It seems that this value is the "Friendly name" field in the // detals tab <-- Certificate window <-- view <-- Certificate // Button <-- Content tab <-- Internet Options <-- Tools menu // In MS IE 6. Enumeration enumas = ks.aliases(); String keyAlias = null; if (enumas.hasMoreElements())// we are readin just one certificate. { keyAlias = (String)enumas.nextElement(); System.out.println("alias=[" + keyAlias + "]"); } // Now once we know the alias, we could get the keys. System.out.println("is key entry=" + ks.isKeyEntry(keyAlias)); PrivateKey prikey = (PrivateKey) ks.getKey(keyAlias, nPassword); Certificate cert = ks.getCertificate(keyAlias); PublicKey pubkey = cert.getPublicKey(); System.out.println("cert class = " + cert.getClass().getName()); System.out.println("cert = " + cert); System.out.println("public key = " + pubkey); System.out.println("private key = " + prikey); return prikey; } catch (Exception e) { e.printStackTrace(); } return null; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值