数字签名Java实现小记

一个证书发放单位给的证书里面包括一个发送单位的公钥,当前用户的一个私钥,公钥可用 Certificate certificate = getCertificate(certificatePath); PublicKey key = certificate.getPublicKey(); 的方法直接获取。私钥需要提交读取密钥库用到的读取密钥和alias名称,KeyStore ks = getKeyStore(keyStorePath, alias, password); PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());
以上是单向认证的机制实现

//做签名
public static String sign(String dataString){
//merPriKeyPath安全证书的文件路径
File f = new File(merPriKeyPath);
kb = new byte[(int)f.length()];
fis = new FileInputStream(f);
fis.read(kb);


PKCS8EncodedKeySpec peks = null;
KeyFactory kf = null;
java.security.PrivateKey pk = null;
peks = new PKCS8EncodedKeySpec(kb);
kf = KeyFactory.getInstance("RSA");
pk = kf.generatePrivate(peks);//获取私钥

byte sb[] = (byte[])null;
sig = Signature.getInstance("SHA1withRSA");
sig.initSign(pk);
sig.update(dataString.getBytes("gb2312"));
sb = sig.sign();


BASE64Encoder base64 = new BASE64Encoder();
String b64Str = base64.encode(sb);

BufferedReader br = new BufferedReader(new StringReader(b64Str));
String tmpStr = "";
String tmpStr1;
for(tmpStr1 = ""; (tmpStr = br.readLine()) != null; tmpStr1 = tmpStr1 + tmpStr);
b64Str = tmpStr1;
return b64Str;

}


//dataString被签名数据,signString签名结果(base64编码)
public static boolean verify(String dataString, String signString){
//读取数字证书文件
String platCertPath="数字证书路径";
FileInputStream fis;
File f = new File(platCertPath);
cb = new byte[(int)f.length()];
fis = new FileInputStream(f);
fis.read(cb);
//使用数字证书
ByteArrayInputStream bais = new ByteArrayInputStream(cb);
CertificateFactory cf = null;
X509Certificate cert = null;

cf = CertificateFactory.getInstance("X.509");
cert = (X509Certificate)cf.generateCertificate(bais);// 取公钥匙对象?
//验证数字签名
BASE64Decoder base64 = new BASE64Decoder();//对签名进行DASE64编码还原
byte signed[] = base64.decodeBuffer(signString);
Signature sig = Signature.getInstance("SHA1withRSA");
sig.initVerify(cert);
sig.update(dataString.getBytes());
return sig.verify(signed);

}




http://crazier9527.iteye.com/blog/396012
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值