欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java读取证书公钥的实现

程序员文章站 2022-07-10 12:36:11
方式1:使用javax.security.cert.x509certificate进行解析url url = demo.class.getclassloader().getresource("c000...

方式1:

使用javax.security.cert.x509certificate进行解析

url url = demo.class.getclassloader().getresource("c000024.crt");  //证书路径
system.out.println("公钥所在路径:"+url.getfile());
x509certificate cert = x509certificate.getinstance(new fileinputstream(url.getfile()));
publickey publickey = cert.getpublickey();
base64encoder base64encoder=new base64encoder();
string publickeystring = base64encoder.encode(publickey.getencoded());
system.out.println("-----------------公钥--------------------");
system.out.println(publickeystring);
system.out.println("-----------------公钥--------------------");

方式2:

使用java.security.cert.x509certificate进行解析

url url = demo.class.getclassloader().getresource("c000024.crt");  //证书路径
system.out.println("公钥所在路径:"+url.getfile());
certificatefactory cf = certificatefactory.getinstance("x.509");
x509certificate cert = (x509certificate)cf.generatecertificate(new fileinputstream(url.getfile()));
publickey publickey = cert.getpublickey(); 
base64encoder base64encoder=new base64encoder();
string publickeystring = base64encoder.encode(publickey.getencoded());
system.out.println("-----------------公钥--------------------");
system.out.println(publickeystring);
system.out.println("-----------------公钥--------------------");

说明:

因为只做示例,没有进行异常处理和流的释放,方式1的代码可能少点,方式2需要强转,美观上可能方式1更好看点,但方式1的实质还是调用的方式2,方式2内部有实现缓存策略。更多可以参考下api文档,文档上有提供示例。

补充:java生成rsa公钥和私钥及rsa对数据的加签和验签

背景:

最近来到了新的公司,公司做的是保险支付相关业务,对接渠道的时候经常会用到数据的加签和验签,初次涉及rsa加签验签,通过网站生成了rsa公钥和私钥,用私钥将我要传送的数据进行了加签,并将我的公钥提供给了渠道方进行验签,结果在联调的时候,验签总是错误,渠道方用自己的私钥对数据加签后再用自己的公钥对数据进行验签却能通过,于是我也用自己的私钥对数据进行加签后再用自己的公钥对数据进行验签,结果让我惊讶,居然没有通过!

到了这里,产生错误的原因基本上已经一目了然了,我通过网站生成的公私钥是无法配对的,这当中可能涉及到了网站生成公私钥的时候已经对公私钥进行了处理,比如说pkcs8的处理,所以决定自己用java来生成rsa公钥和私钥进行验证测试,文档写出来了,测试结果自然已经知道了,是通过的。

以下为完整的验签过程:

启动类:zhongbaohuiapplication.java

package com.test.zhongbaohui; 
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication; 
@springbootapplication
public class zhongbaohuiapplication {
 
  public static void main(string[] args) {
    springapplication.run(zhongbaohuiapplication.class, args);
  }
}

请求controller:requestcontroller.java

package com.test.zhongbaohui.controller; 
import com.alibaba.fastjson.jsonobject;
import com.test.zhongbaohui.utils.rsasignutils;
import lombok.extern.slf4j.slf4j;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller; 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.util.hashmap;
import java.util.map;
 
/**
 * @program: zhongbaohui
 * @package: com.test.zhongbaohui.controller
 * @description:
 * @auther: chengjunyu
 * @createdate: 2019/12/6 22:05
 */
@restcontroller
@requestmapping(value="/test")
@slf4j
public class requestcontroller {
 
  @autowired
  private responsecontroller responsecontroller; 
  @postmapping("/getjsonobject")
  private string getjsonobject(httpservletrequest request, httpservletresponse response) {
 
    jsonobject jsonobject = new jsonobject();
    jsonobject.put("signtype", "rsa");
    jsonobject.put("enterpriseid", "201975538583911110");
    jsonobject.put("nonce", "b0eed33073664f5fa983c5b774dbd4b6");
    jsonobject.put("timestamp", "2019-12-07 01:19:25");
    map<string, object> map = new hashmap<>();
    map.put("bankcode", "其他");
    map.put("batchno", "201975538583911110b1084fa29f6c");
    map.put("bankcardnumber", "6217856100077026406");
    map.put("paymentnote", "佣金发放");
    map.put("idcardnumber", "320123199103104650");
    map.put("mobile", "15365176555");
    map.put("bankname", "中国银行");
    map.put("outenterpriseorderno", "t20191207011545663692017");
    map.put("realpayment", "1.00");
    map.put("serviceid", "201968613430727001");
    map.put("username", "程俊予");
    jsonobject.put("data", map);
    //私钥内容
    string privatekey = "miicdwibadanbgkqhkig9w0baqefaascamewggjdagfnoid56ynquwenrgnw1ud+gbcsfojpoy00+tyq/qhvaprgpeuklacbebkyj4+g3h4t7e1dtoblqtzk/yi+2vcbdnhhql3uvdklkvmrxxcbpbjtjso3rmmjfc6ocikfzhujhhio7mjwwrmyltagmbaaecgybplzud/czv1klzia5bdbf2yk36fyoc3hl3ixleiyp91ngc6hqhfseyxphvrzp0aaym9ic824bjq4gg7pkkhzyt3igdcqqyodbycdof8jsk9t0g0ll7g1dlqwl9r6+savauf5rubwz5byos6cnfbybfqadrudf96yh0hw0qf1u8xqjbaprphvzpeoznsy/m1wljzv5gv1ooi9s+pzgjqhgwbt7faipdkziaa7b6hgnbgua7m4vezgjnaohxhdl1qmtltjmcqqd3vinif9ejkzn7lncpqsl1akxbwuxjtmceeux43lcdapgq+4y6g5qu3fhwzxwsdznublqjwzfgxw/f2e2dxopfakbxgergfsid7kppqudysqel2p8dsjixtiku2ny6regrnait5ktnvfrn/stxiduhamc+k0kevhi9xwqz9ip0kggjakea3huzzywup3oyhzhhn5vrx1yuikgkku3nsday9b+323sezoljooom+qhdljkp0saas+sbqfqrqka7q/yqxdwd4wjbaiuxethfnmr3u9fetkhmwkwoph23ehm0xpdvzmcb24wwk7qaxcmo71ugg6qqmba+wycrjpwbmu5xysb5+d5znc0=";
    string sign = rsasignutils.sign(jsonobject, privatekey);
    log.info("验签sign为:{}", sign);
    jsonobject.put("sign", sign);
    string message = responsecontroller.returnmsg(jsonobject.tojsonstring());
    return message;
  }
}

响应controller:responsecontroller.java

package com.test.zhongbaohui.controller; 
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;
import com.test.zhongbaohui.utils.rsasignutils;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.restcontroller;
 
/**
 * @program: zhongbaohui
 * @package: com.test.zhongbaohui.controller
 * @description:
 * @auther: chengjunyu
 * @createdate: 2019/12/7 20:46
 */
@restcontroller
@slf4j
public class responsecontroller {
  @postmapping("/returnmsg")
  public string returnmsg(string message) {
    jsonobject jsonobject = jsonobject.parseobject(message);
    log.info("接受请求内容为:{}", jsonobject.tojsonstring());
    string sign = jsonobject.getstring("sign");
    jsonobject.remove("sign");
    string publickey = "migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqd5gn/eanlyf6xzzia+emdarshp64j1tvhfhgxehaizzmnnpk2kv6h1wqaxj3ripqhaxm5mo+phtx+le3tq0zm5ulwzp8ovtlxgw54r0jd1fxzc5ftev1wgtwsby0qn0tdcrqujgoin84bo4yyqozcvlqzgc7qidaqab";
    boolean flag = rsasignutils.verify(jsonobject, publickey, sign);
    jsonobject object = new jsonobject();
    if(flag) {
      object.put("code", "200");
      object.put("status", "success");
      object.put("message:", "验签成功");
    }else {
      object.put("code", "400");
      object.put("status", "failure");
      object.put("message:", "验签失败");
    }
    return object.tojsonstring();
  }
}

rsa工具类:rsasignutils.java

package com.test.zhongbaohui.utils; 
import com.alibaba.fastjson.jsonobject;
import lombok.extern.slf4j.slf4j;
import org.apache.tomcat.util.codec.binary.base64;
import org.springframework.stereotype.component;
import sun.misc.base64decoder;
import sun.misc.base64encoder; 
import java.io.ioexception;
import java.io.unsupportedencodingexception;
import java.security.*;
import java.security.interfaces.rsaprivatekey;
import java.security.interfaces.rsapublickey;
import java.security.spec.invalidkeyspecexception;
import java.security.spec.pkcs8encodedkeyspec;
import java.security.spec.x509encodedkeyspec;
import java.util.hashmap;
import java.util.map;
 
/**
 * @program: zhongbaohui
 * @package: com.test.zhongbaohui.controller
 * @description:
 * @auther: chengjunyu
 * @createdate: 2019/12/6 23:03
 */
@slf4j
@component
public class rsasignutils { 
  public static final string key_algorithm = "rsa";
  private static final string public_key = "rsapublickey";
  private static final string private_key = "rsaprivatekey";
  public static final string signature_algorithm="md5withrsa";
  public static final integer rsa_key_size = 1024;
 
  /*
   * @function: 使用字符串格式的私钥为jsonobject格式的内容加签
   * @param: [jsonobject, privatekey]
   * @return: java.lang.string
   * @auther: chengjunyu
   * @date: 2019/12/7 21:06
   */
  public static string sign(jsonobject jsonobject, string privatekey) {
    string signmsg = "";
    string data = jsonobject.tostring();
    log.info("加签对象内容为:{}", data);
    try {
      byte[] keybytes = decryptbase64(privatekey);
      pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(keybytes);
      keyfactory keyfactory = keyfactory.getinstance("rsa");
      privatekey key = keyfactory.generateprivate(keyspec);
      signature signature = signature.getinstance("md5withrsa");
      signature.initsign(key);
      signature.update(data.getbytes("iso-8859-1"));
      signmsg = base64.encodebase64string(signature.sign());
    } catch (exception var8) {
      var8.printstacktrace();
    }
    return signmsg;
  }
 
  /*
   * @function: 使用字符串格式的公钥为jsonobject格式的内容验签
   * @param: [jsonobject, publickey, sign]
   * @return: boolean
   * @auther: chengjunyu
   * @date: 2019/12/8 14:56
   */
  public static boolean verify(jsonobject jsonobject, string publickey, string sign) {
    string s = jsonobject.tojsonstring();
    log.info("s:{}",s);
    boolean rs = false;
    try {
      byte[] keybytes = decryptbase64(publickey);
      x509encodedkeyspec keyspec = new x509encodedkeyspec(keybytes);
      keyfactory keyfactory = keyfactory.getinstance("rsa");
      publickey key = keyfactory.generatepublic(keyspec);
      signature signature = signature.getinstance("md5withrsa");
      signature.initverify(key);
      signature.update(s.getbytes("iso-8859-1"));
      return signature.verify(base64.decodebase64(sign.getbytes()));
    } catch (exception var9) {
      var9.printstacktrace();
      return rs;
    }
  }
 
  /*
   * @function: 获取publickey格式的公钥,本例中未使用
   * @param: [key]
   * @return: java.security.publickey
   * @auther: chengjunyu
   * @date: 2019/12/8 16:10
   */
  public static publickey getpublickey(string key) {
    publickey publickey = null;
    try {
      byte[] keybytes = (new base64decoder()).decodebuffer(key);
      x509encodedkeyspec keyspec = new x509encodedkeyspec(keybytes);
      // rsa对称加密算法
      keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
      // 取公钥匙对象
      publickey = keyfactory.generatepublic(keyspec);
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    } catch (invalidkeyspecexception e) {
      e.printstacktrace();
    } catch (ioexception e) {
      e.printstacktrace();
    }
    return publickey;
  } 
 
  /*
   * @function: 获取publickey格式的私钥,本例中未使用
   * @param: [key]
   * @return: java.security.privatekey
   * @auther: chengjunyu
   * @date: 2019/12/8 16:10
   */
  public static privatekey getprivatekey(string key) {
    privatekey privatekey = null;
    try {
      byte[] keybytes = (new base64decoder()).decodebuffer(key);
      pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(keybytes);
      keyfactory keyfactory = keyfactory.getinstance(key_algorithm);
      privatekey = keyfactory.generateprivate(keyspec);
    } catch (ioexception e) {
      e.printstacktrace();
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    } catch (invalidkeyspecexception e) {
      e.printstacktrace();
    }
    return privatekey;
  }
 
  /*
   * @function: 初始化公钥和私钥
   * @param: []
   * @return: java.util.map<java.lang.string,java.lang.object>
   * @auther: chengjunyu
   * @date: 2019/12/8 14:34
   */
  public static map<string, object> initkey() {
    keypairgenerator keypairgen = null;
    try {
      keypairgen = keypairgenerator.getinstance(key_algorithm);
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    }
    keypairgen.initialize(rsa_key_size);
    keypair keypair = keypairgen.generatekeypair();
    rsapublickey publickey = (rsapublickey) keypair.getpublic();
    rsaprivatekey privatekey = (rsaprivatekey) keypair.getprivate();
    map<string, object> keymap = new hashmap<string, object>(2);
    keymap.put(public_key, publickey);
    keymap.put(private_key, privatekey);
    return keymap;
  }
 
  //获得公钥字符串
  public static string getpublickeystr(map<string, object> keymap) {
    //获得map中的公钥对象 转为key对象
    key key = (key) keymap.get(public_key);
    //编码返回字符串
    return encryptbase64(key.getencoded());
  }
 
  //获得私钥字符串
  public static string getprivatekeystr(map<string, object> keymap) {
    //获得map中的私钥对象 转为key对象
    key key = (key) keymap.get(private_key);
    //编码返回字符串
    return encryptbase64(key.getencoded());
  }
 
  //编码返回字符串
  public static string encryptbase64(byte[] key) {
    return (new base64encoder()).encodebuffer(key);
  }
 
  //解码返回byte
  public static byte[] decryptbase64(string key) {
    byte[] bytes = null;
    try {
      return (new base64decoder()).decodebuffer(key);
    } catch (ioexception e) {
      return bytes;
    }
  }
 
  public static void main(string[] args) {
    map<string, object> keymap = initkey();
    string publickey = getpublickeystr(keymap);
    log.info("java生成rsa公钥:{}", publickey);
    string privatekey = getprivatekeystr(keymap);
    log.info("java生成rsa私钥:{}", privatekey);
  }
}

注意:

本文中请求和响应类中的私钥和公钥均是不完整的,在请求和响应类中的私钥和公钥由rsasignutils工具类生成后,再替代入请求和响应类中,请求类中使用私钥加签,响应类中使用公钥验签。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。