数字签名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

你可能感兴趣的:(java,Security,Blog,F#)