美文网首页IT必备技能小技巧
java读取jks证书获取私钥和公钥/签名和验签

java读取jks证书获取私钥和公钥/签名和验签

作者: 慢慢淡忘 | 来源:发表于2019-01-23 17:00 被阅读0次

    环境

    WINDOWS OS
    jdk 1.8_64
    

    获取公钥和私钥

    String jksPath = ""; //jks file path
    String jksPassword = ""; // jks keyStore password
    String certAlias = ""; // cert alias
    String certPassword = ""; // cert password
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());
    PriateKey privateKey = (PrivateKey) keyStore.getKey(certAlias, certPassword.toCharArray());
    PublicKey publicKey = keyStore.getCertificate(certAlias).getPublicKey();
    

    签名

    String signData = ""; //需要签名的内容
    String signAlg = "SHA256withRSA"; //签名类型
    Signature signature = Signature.getInstance(signAlg);
    signature.initSign(privateKey);
    signature.update(signData.getBytes());
    String signedData = Base64.getEncoder().encodeToString(signature.sign().replace("\r\n","").replace("\n",""));
    
    

    验签

    String signData = ""; //需要签名的内容
    String signedData = ""; //签名后的内容
    String signAlg = "SHA256withRSA"; //签名类型
    Signature signature = Signature.getInstance(signAlg);
    signature.initVerify(publicKey);
    signature.update(signData.getBytes());
    boolean isVerify = signature.verify(Base64.getDecoder().decode(signedData));
    

    相关文章

      网友评论

        本文标题:java读取jks证书获取私钥和公钥/签名和验签

        本文链接:https://www.haomeiwen.com/subject/cjqsjqtx.html