SHA256withRSA证书签名,私钥签名/公钥验签(证书文件加载公私钥)

https://www.cnblogs.com/jinzhiming/p/10576385.html

证书签名

复制代码

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.Enumeration;

/**
 * 私钥签名,公钥验签
 * @author jinzhm
 *
 */
public class SignUtil {
    private static String CHARSET_ENCODING = "UTF-8";
    private static String ALGORITHM = "SHA256withRSA";
    
    /**
     * 签名
     * @param srcData
     * @param privateKeyPath
     * @param privateKeyPwd
     * @return
     */
    public static String sign(String srcData, String privateKeyPath, String privateKeyPwd){
        if(srcData==null || privateKeyPath==null || privateKeyPwd==null){
            return "";
        }
        try {
            // 获取证书的私钥
            PrivateKey key = readPrivate(privateKeyPath, privateKeyPwd);
            // 进行签名服务
            Signature signature = Signature.getInstance(ALGORITHM);
            signature.initSign(key);
            signature.update(srcData.getBytes(CHARSET_ENCODING));
            byte[] signedData = signature.sign();
            return Base64.getEncoder().encodeToString(signedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 验签
     * @param srcData
     * @param signedData
     * @param publicKeyPath
     * @return
     */
    public static boolean verify(String srcData, String signedData, String publicKeyPath){
        if(srcData==null || signedData==null || publicKeyPath==null){
            return false;
        }
        try {
            PublicKey publicKey = readPublic(publicKeyPath);
            Signature sign = Signature.getInstance(ALGORITHM);
            sign.initVerify(publicKey);
            sign.update(srcData.getBytes(CHARSET_ENCODING));
            return sign.verify(Base64.getDecoder().decode(signedData));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    

    /**
     * 读取公钥
     * @param publicKeyPath
     * @return
     */
    private static PublicKey readPublic(String publicKeyPath){
        if(publicKeyPath==null){
            return null;
        }
        PublicKey pk = null;
        FileInputStream bais = null;
        try {
            CertificateFactory certificatefactory = CertificateFactory.getInstance("X.509");
            bais = new FileInputStream(publicKeyPath);
            X509Certificate cert = (X509Certificate)certificatefactory.generateCertificate(bais);
            pk = cert.getPublicKey();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally{
            if(bais != null){
                try {
                    bais.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return pk;
    }
    
    /**
     * 读取私钥
     * @param path
     * @return
     */
    private static PrivateKey readPrivate(String privateKeyPath, String privateKeyPwd){
        if(privateKeyPath==null || privateKeyPwd==null){
            return null;
        }
        InputStream stream = null;
        try {
            // 获取JKS 服务器私有证书的私钥,取得标准的JKS的 KeyStore实例
            KeyStore store = KeyStore.getInstance("JKS");
            stream = new FileInputStream(new File(privateKeyPath));
            // jks文件密码,根据实际情况修改
            store.load(stream, privateKeyPwd.toCharArray());
            // 获取jks证书别名
            Enumeration en = store.aliases();
            String pName = null;
            while (en.hasMoreElements()) {
                String n = (String) en.nextElement();
                if (store.isKeyEntry(n)) {
                    pName = n;
                }
            }
            // 获取证书的私钥
            PrivateKey key = (PrivateKey) store.getKey(pName,
                    privateKeyPwd.toCharArray());
            return key;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(stream != null){
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}

复制代码

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是SHA256withRSA签名验签的Java代码示例: **签名代码:** ``` import java.security.*; import java.util.Base64; public class RSASignatureExample { public static void main(String[] args) throws Exception { String message = "This is a message to be signed."; // Generate key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); // Create a signature object Signature signature = Signature.getInstance("SHA256withRSA"); // Initialize the signature object with the private key PrivateKey privateKey = keyPair.getPrivate(); signature.initSign(privateKey); // Update the signature object with the message signature.update(message.getBytes()); // Sign the message byte[] signatureBytes = signature.sign(); // Print the signature in Base64 encoding System.out.println("Signature: " + Base64.getEncoder().encodeToString(signatureBytes)); } } ``` **验签代码:** ``` import java.security.*; import java.util.Base64; public class RSASignatureExample { public static void main(String[] args) throws Exception { String message = "This is a message to be signed."; String signatureString = "PLl6yBb6IhOv0Jd3k1y/YlR9a3UOx0WJQy6RbbS/3W8mQ2ztcL5x+JShHl6O8gTlJn4wtNQ7Ggz0ZiPwq9SInQf/9d4eG4qSkZCzVgP9U9bQY7jwFVhWXfzqU6l5K8SxyA2pBw+PQs0N2dJQ2Xk9V3tXZP5h+UcMXwLQe/3K7uh2M="; // Generate key pair KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair keyPair = keyGen.generateKeyPair(); // Create a signature object Signature signature = Signature.getInstance("SHA256withRSA"); // Initialize the signature object with the public key PublicKey publicKey = keyPair.getPublic(); signature.initVerify(publicKey); // Update the signature object with the message signature.update(message.getBytes()); // Verify the signature boolean verified = signature.verify(Base64.getDecoder().decode(signatureString)); // Print the verification result System.out.println("Signature verified: " + verified); } } ``` 以上代码示例中,我们使用SHA256withRSA算法对一个字符串进行签名验签。在签名时,我们首先生成了一个RSA密钥对,然后使用私钥对消息进行签名,并打印出Base64编码的签名结果。在验签时,我们使用同样的RSA密钥对和签名算法,使用公钥初始化签名对象,并使用该对象对消息进行验证,最终打印验证结果。需要注意的是,验签时需要将签名结果从Base64编码中解码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值