IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> java使用bountycastle验证rsa公钥和证书,使用bountycastle处理pem格式密钥 -> 正文阅读

[网络协议]java使用bountycastle验证rsa公钥和证书,使用bountycastle处理pem格式密钥

java验证公钥和证书
验证签名
验证签名
项目需求:通过私钥签名,公钥验证判断公钥和私钥是否配对

下面代码是通过私钥(公钥)加密,公钥(私钥)解密,通过前后对比加密数据是否一致得出配对结果。与项目需求不一致,因此重新改动一些。

项目在加入验证签名之后会出现Signature length not correct错误,是由于在转换格式的过程中出现使用getBytes函数,使得签名长度发生改变导致。
修改Signature length not correct错误
错误原因

介绍一下编码格式

本节主要介绍密钥和证书中常见的编码规则 DER和由 DER 衍生出的密钥文件格式 PEM。

DER (Distinguished Encoding Rules)DER (Distinguished Encoding Rules)

DER 是用二进制DER编码的证书,DER格式常见于java语言

PEM格式是在DER格式的基础上采用base64编码得到,PEM is Base64-encoded DER。PEM格式是采用openssl生成密钥和证书的格式。
下面是经典的PEM格式

PEM = "-----BEGIN PUBLIC KEY-----" 
  encode_base64(decode_hex(DER)) 
   "-----END PUBLIC KEY-----"

公钥密码学标准 PKCS (Public Key Cryptography Standards) 和公钥基础设施 PKIX(Public-Key Infrastructure X.509) 等使用 ASN.1 的类型定义密钥和证书的格式和编码,以描述公私钥和证书属性。 需要注意,PKCS 虽然名字是公钥密码学标准,它其实也包括私钥格式标准。

PKCS#1 格式

使用openssl genrsa生成的密钥对即是PKCS#1格式

-----BEGIN RSA PRIVATE KEY-----
....
-----END RSA PRIVATE KEY-----
PKCS#8 格式
-----BEGIN PRIVATE KEY-----
....
-----END PRIVATE KEY-----
package cc.weno.util;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKey;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.*;
import java.nio.charset.Charset;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * openssl 证书公钥私钥读取加密解密工具类,主要用于验证上传的openssl 生成的证书和私钥文件是否正确的问题
 *
 * @author yinliang 2018.12.13 add
 * 主要逻辑:
 * 1、根据私钥文件读取私钥
 * 2、根据公钥文件读取公钥
 * 3、根据证书文件读取公钥
 * 4、根据证书公钥加密字符串
 * 5、根据证书私钥解密字符串
 * 6、如果字符串经过证书公钥加密后,再根据证书私钥解密后能后还原,说明上传的证书和私钥是正确的
 */
public class OpensslUtils {
    private static final String DEFAULT_ENCODING = "UTF-8";

    private static final Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_ENCODING);

    private static final String KEY_ALGORITHM = "RSA";
    /**
     * 默认是RSA/NONE/PKCS1Padding
     */
    private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding";

    /**
     * RSA密钥长度必须是64的倍数,在512~65536之间。默认是1024
     */
    private static final int KEY_SIZE = 1024;

    /**
     * RSA最大加密明文大小:明文长度(bytes) <= 密钥长度(bytes)-11
     */
    private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8;

    private static Logger logger = Logger.getLogger(OpensslUtils.class);
    /**
     * 利用开源的工具类解析openssl私钥,openssl私钥文件格式为pem,需要去除页眉页脚后才能被java读取
     *
     * @param file
     * @return
     */
    public static PrivateKey getPrivateKey(File file) {
        if (file == null) {
            return null;
        }
        PrivateKey privKey = null;
        PemReader pemReader = null;
        try {
            pemReader = new PemReader(new FileReader(file));
            PemObject pemObject = pemReader.readPemObject();
            byte[] pemContent = pemObject.getContent();
            //支持从PKCS#1或PKCS#8 格式的私钥文件中提取私钥
            if (pemObject.getType().endsWith("RSA PRIVATE KEY")) {
                // 取得私钥  for PKCS#1
                RSAPrivateKey asn1PrivKey = RSAPrivateKey.getInstance(pemContent);
                RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
                KeyFactory keyFactory= KeyFactory.getInstance("RSA");
                privKey= keyFactory.generatePrivate(rsaPrivKeySpec);
            } else if (pemObject.getType().endsWith("PRIVATE KEY")) {
                //取得私钥 for PKCS#8
                PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemContent);
                KeyFactory kf = KeyFactory.getInstance("RSA");
                privKey = kf.generatePrivate(privKeySpec);
            }
        } catch (FileNotFoundException e) {
            logger.error("read private key fail,the reason is the file not exist");
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("read private key fail,the reason is :"+e.getMessage());
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            logger.error("read private key fail,the reason is :"+e.getMessage());
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            logger.error("read private key fail,the reason is :"+e.getMessage());
            e.printStackTrace();
        }  finally {
            try {
                if (pemReader != null) {
                    pemReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return privKey;
    }

    /**
     * 利用java自带的方法读取openssl私钥,openssl私钥文件格式为pem,需要去除页眉页脚后,再进行base64位解码才能被java读取
     * 注意该方法有缺陷,只是简单的根据注释将页眉页脚去掉了,不是很完善,如果页眉页脚前面有空格和注释的情况的会有问题,保留此方法是为方便弄清楚openssl私钥解析原理
     *
     * @param file
     * @return
     */
    public static PrivateKey getPrivateKey1(File file) {
        if (file == null) {
            return null;
        }
        PrivateKey privKey = null;
        try {
            BufferedReader privateKey = new BufferedReader(new FileReader(
                    file));
            String line = "";
            String strPrivateKey = "";
            while ((line = privateKey.readLine()) != null) {
                if (line.contains("--")) {//过滤掉首尾页眉页脚
                    continue;
                }
                strPrivateKey += line;
            }
            privateKey.close();
            ;
            //使用base64位解码
            byte[] privKeyByte = Base64.decodeBase64(strPrivateKey);
            //私钥需要使用pkcs8格式编码
            PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyByte);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            privKey = kf.generatePrivate(privKeySpec);
            return privKey;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        return privKey;
    }


    /**
     * 从证书文件获取公钥
     *
     * @param file
     * @return
     * @throws CertificateException
     * @throws FileNotFoundException
     */
    public static PublicKey getPublicKeyFromCert(File file) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream in = new FileInputStream(file);
            Certificate crt = cf.generateCertificate(in);
            PublicKey publicKey = crt.getPublicKey();
            return publicKey;
        } catch (CertificateException e) {
            logger.error("read public key fail,the reason is :"+e.getMessage());
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            logger.error("read public key fail,the reason is the file not exist");
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 从openssl公钥文件中读取公钥
     * @param file
     * @return
     */
    public static PublicKey getPublicKey(File file) {
        if (file == null) {
            return null;
        }
        PublicKey pubKey = null;
        PemReader pemReader = null;
        try {
            pemReader = new PemReader(new FileReader(file));
            PemObject pemObject = pemReader.readPemObject();
            byte[] pemContent = pemObject.getContent();
            //公钥需要使用x509格式编码
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemContent);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            pubKey = kf.generatePublic(pubKeySpec);
            return pubKey;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } finally {
            try {
                if (pemReader != null) {
                    pemReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pubKey;
    }



    /**
     * 加密
     *
     * @param key
     * @param plainBytes
     * @return
     */
    public static byte[] encrypt(PublicKey key, byte[] plainBytes) {

        ByteArrayOutputStream out = null;
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);

            int inputLen = plainBytes.length;
            if (inputLen <= MAX_ENCRYPT_BLOCK) {
                return cipher.doFinal(plainBytes);
            }
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 数据太长对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(plainBytes, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(plainBytes, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            return out.toByteArray();
        } catch (NoSuchAlgorithmException e) {
            logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (NoSuchPaddingException e) {
            logger.error("rencrypt fail,the reason is :"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (BadPaddingException e) {
            logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) out.close();
            } catch (Exception e2) {
            }
        }
    }

    /**
     * 根据公钥加密字符串
     *
     * @param key
     * @param plainText 需要加密的字符串
     * @return
     */
    public static String encrypt(PublicKey key, String plainText) {
        byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET));
        return Base64.encodeBase64String(encodeBytes);
    }

    /**
     * 解密
     *
     * @param key
     * @param encodedText
     * @return
     */
    public static String decrypt(PrivateKey key, byte[] encodedText) {

        ByteArrayOutputStream out = null;
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            int inputLen = encodedText.length;

            if (inputLen <= MAX_DECRYPT_BLOCK) {
                return new String(cipher.doFinal(encodedText), DEFAULT_CHARSET);
            }

            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encodedText, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encodedText, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            return new String(out.toByteArray(), DEFAULT_CHARSET);
        } catch (NoSuchAlgorithmException e) {
            logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (NoSuchPaddingException e) {
            logger.error("rencrypt fail,the reason is :"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (IllegalBlockSizeException e) {
            logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } catch (BadPaddingException e) {
            logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (out != null) out.close();
            } catch (Exception e2) {
            }
        }
    }

    /**
     * 根据私钥解密加密过的字符串
     *
     * @param key
     * @param encodedText 加密过的字符串
     * @return 解密后的字符串
     */
    public static String decrypt(PrivateKey key, String encodedText) {
        byte[] bytes = Base64.decodeBase64(encodedText);
        return decrypt(key, bytes);
    }

    /**
     * 验证证书
     * @param cert
     * @return
     */
    public static String validateCert(File cert){
        if (cert == null) {
            return "证书CRT文件不能为空";
        }
        PublicKey publicKey = getPublicKeyFromCert(cert);
        if (publicKey == null) {
            return "无法读取证书公钥,证书CRT文件格式错误";
        }
        return null;
    }

    /**
     * 验证私钥
     * @param privateKey
     * @return
     */
    public static String validatePrivateKey( File privateKey){
        if (privateKey == null) {
            return "证书私钥不能为空";
        }
        PrivateKey privKey = getPrivateKey(privateKey);
        if (privKey == null) {
            return "无法读取证书私钥,证书私钥文件格式错误";
        }
        return null;
    }

    /**
     * 验证证书私钥是否匹配,如果不匹配返回错误消息
     * @param cert
     * @param privateKey
     * @return 错误消息
     */
    public static String validate(File cert, File privateKey) {
        String res = validateCert(cert);//验证证书
        if((res!=null)&&(res.length()>0)){
            return res;//返回错误消息
        }
        res = validatePrivateKey(privateKey);//验证私钥
        if((res!=null)&&(res.length()>0)){
            return res;//返回错误消息
        }
        PublicKey publicKey = getPublicKeyFromCert(cert);
        PrivateKey privKey = getPrivateKey(privateKey);
        String str = "你好";//测试字符串
        String encryptStr = OpensslUtils.encrypt(publicKey, str);//根据证书公钥对字符串进行加密
        String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);//根据证书私钥对加密字符串进行解密
        System.out.println(decryptStr);
        if(!str.equals(decryptStr)){//字符串根据证书公钥加密,私钥解密后不能还原说明证书与私钥不匹配
            return "证书与私钥不匹配";
        }
        return "ok";
    }

    /**
     * 测试主方法
     *
     * @param args
     */
    public static void main(String[] args) {
        File privateKeyFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\rootca.key");
//        PrivateKey privKey = OpensslUtils.getPrivateKey(privateKeyFile);
//        System.out.println("privKey1:" + privKey);
//        privKey = OpensslUtils.getPrivateKey1(privateKeyFile);
//        System.out.println("privKey2:" + privKey);
//        File publicKeyFile = new File("src/main/resources/test.public.key");
//        PublicKey publicKey = OpensslUtils.getPublicKey(publicKeyFile);
//        System.out.println("publicKey:" + publicKey);
        File certFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\rootca.pem");
        //publicKey = OpensslUtils.getPublicKeyFromCert(certFile);
//        System.out.println("publicKey2:" + publicKey);
//        String str = "haha";
//        String encryptStr = OpensslUtils.encrypt(publicKey, str);
//        System.out.println("encryptStr:" + encryptStr);
//        String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);
//        System.out.println("decryptStr:" + decryptStr);
        String validateResult = validate(certFile,privateKeyFile);
        System.out.println("validateResult:" + validateResult);
    }
}

下面是根据项目需求新增加的改动,通过私钥签名,公钥签名验证

public static boolean checkSign( String message, String sign, File cert )
    {
        boolean ret = false;


        {
            try {
                ret = OpensslUtils.verify( message, sign, getPublicKeyFromCert(cert));
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (SignatureException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return ret;
    }
    private static PublicKey getKey( File keyPath )
            throws NoSuchAlgorithmException, IOException, InvalidKeySpecException
    {
        final KeyFactory keyFactory = KeyFactory.getInstance( "RSA");
        final PemReader reader = new PemReader( new FileReader( keyPath ) );
        final byte[] pubKey = reader.readPemObject(  ).getContent(  );
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec( pubKey );

        return keyFactory.generatePublic( publicKeySpec );
    }
    private static boolean verify( String message, String sign, PublicKey publicKey )
            throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException
    {
        final Signature sig = Signature.getInstance("MD5withRSA");
        sig.initVerify( publicKey );
        sig.update( message.getBytes("utf-8") );

        //final byte[] bytes = Base64Decoder.decode( URLDecoder.decode( sign, "utf-8") );
        byte[] signByte = Base64.decodeBase64(sign);
        return sig.verify(signByte );
    }
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateK);
        signature.update(data);
        return Base64.encodeBase64String(signature.sign());
    }
    /**
     * 测试主方法
     *
     * @param args
     */

    public static void main(String[] args) {
        File certFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\client.pem");
        String str = "sdifhjksabdnkfbasdjhhh";
        File privateKeyFile = new File("C:\\Users\\ASUS\\Desktop\\CA\\client.key");
        PrivateKey privKey = getPrivateKey(privateKeyFile);
        String encryptStr = OpensslUtils.encrypt(privKey, str);
        String sign = null;

        {
            try {
                sign = OpensslUtils.sign(encryptStr.getBytes(StandardCharsets.UTF_8), Base64.encodeBase64String(privKey.getEncoded()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        boolean bl = checkSign(encryptStr, sign, certFile);
        System.out.println(bl);
    }
  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-10-12 23:49:56  更:2021-10-12 23:50:11 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 4:49:40-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码