Java基于OpenSSL生成 RSA 公私钥对数据进行加解密

  1. 使用OpenSSL来生成私钥和公钥
    1. 验证机器上是否安装openssl

      命令:openssl version -a

      [root@node00 test]# openssl version -a
      OpenSSL 1.0.2k-fips  26 Jan 2017
      built on: reproducible build, date unspecified
      platform: linux-x86_64
      options:  bn(64,64) md2(int) rc4(16x,int) des(idx,cisc,16,int) idea(int) blowfish(idx) 
      compiler: gcc -I. -I.. -I../include  -fPIC -DOPENSSL_PIC -DZLIB -DOPENSSL_THREADS -D_REENTRANT -DDSO_DLFCN -DHAVE_DLFCN_H -DKRB5_MIT -m64 -DL_ENDIAN -Wall -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches   -m64 -mtune=generic -Wa,--noexecstack -DPURIFY -DOPENSSL_IA32_SSE2 -DOPENSSL_BN_ASM_MONT -DOPENSSL_BN_ASM_MONT5 -DOPENSSL_BN_ASM_GF2m -DRC4_ASM -DSHA1_ASM -DSHA256_ASM -DSHA512_ASM -DMD5_ASM -DAES_ASM -DVPAES_ASM -DBSAES_ASM -DWHIRLPOOL_ASM -DGHASH_ASM -DECP_NISTZ256_ASM
      OPENSSLDIR: "/etc/pki/tls"
      engines:  rdrand dynamic 
      [root@node00 test]# 
      
    2. 生成私钥

      openssl genrsa -out rsa_private_key.pem 2048

      openssl随机生成了一份私钥,加密长度是1024位。加密长度是指理论上最大允许”被加密的信息“长度的限制,也就是明文的长度限制。随着这个参数的增大(比方说2048),允许的明文长度也会增加,但同时也会造成计算复杂度的极速增长。一般推荐的长度就是1024位(128字节)。

      查看私钥文件:rsa_private_key.pem,内容都是标准的ASCII字符,开头一行和结尾一行有明显的标记,真正的私钥数据是中间的不规则字符。

      [root@node00 test]# cat rsa_private_key.pem 
      -----BEGIN RSA PRIVATE KEY-----
      MIICXwIBAAKBgQD3g6KX0M0pM5HdC39verZMxDmLyQZ4trDCpmn+DMB3yTf4aVPL
      dgBHhqiw9bnyOwltqlzSlZyr/8jcwimC2pOg9mP8PT8e5NcoqINkcFYwLAlwGDix
      TdKLF0+7HcwfIqJPpX+4WRdsBc2r6Tqr2OlrgKCLQsLbMplaRjPnsBqGDwIDAQAB
      AoGBANTCy64yp1jGYpkfPBEI69G7TzgwuiZj7De2MyBVt9CAIGOhro0TxxO01icf
      YxKs2uLw8c93GfDj87aIFITN/N1MiwVjF9hTxacYkQ2KKiks2kNv5UjHcfgQVpj3
      rfSADJ4NEeV52cp3VHVrF8n+cjvct6boMa7/f6StvfewUxL5AkEA/N8sKmbvTRgM
      DE+vEI06U0Hv5bsGyppbt964WhCwBhzvHX4SZypcmuu3AkQX60ep9Sz8/0JZcJXr
      ZEfEs402RQJBAPqTftznOuC7Uoyh+ogyxYJ1mmO4TnTdh5RqTVbC9DUvxtUtUgqP
      JJRaj+GSoZ+f0+99l1NaqoOtVkq226UmKkMCQQChW1sYV4SdohmWBYbFPgkYtXt6
      EUS9JZAfHQxv1DQuQmpGXHsrv3lGFeE6ne7RYHJQE3wA+fqOf+urmqwmkpYtAkEA
      x5FZZM600e/fWypWwsrNC45mnC1aLzGQnd/cING8de/LSFWEFezTkWRfW6TRHLTK
      st8v+q8nRyByrabdYLb4yQJBAIruwdUxt9meTuJgN/YkijCt6Jc8+sOAmSep0G5i
      gcAvSdn7hlRx/jj1FRA5MhSmGmeJdoDlAcWUBaHR/elOedU=
      -----END RSA PRIVATE KEY-----
      
    3. 根据私钥生产公钥

      openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout

      查看公钥:

      [root@node00 test]# cat rsa_public_key.pem 
      -----BEGIN PUBLIC KEY-----
      MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD3g6KX0M0pM5HdC39verZMxDmL
      yQZ4trDCpmn+DMB3yTf4aVPLdgBHhqiw9bnyOwltqlzSlZyr/8jcwimC2pOg9mP8
      PT8e5NcoqINkcFYwLAlwGDixTdKLF0+7HcwfIqJPpX+4WRdsBc2r6Tqr2OlrgKCL
      QsLbMplaRjPnsBqGDwIDAQAB
      -----END PUBLIC KEY-----
      
    4. PKCS#8编码

      指明输入私钥文件为rsa_private_key.pem,输出私钥文件为pkcs8_rsa_private_key.pem,不采用任何二次加密(-nocrypt)

      openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

      查看PKCS#8编码私钥:

      [root@node00 test]# cat pkcs8_rsa_private_key.pem 
      -----BEGIN PRIVATE KEY-----
      MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBAPeDopfQzSkzkd0L
      f296tkzEOYvJBni2sMKmaf4MwHfJN/hpU8t2AEeGqLD1ufI7CW2qXNKVnKv/yNzC
      KYLak6D2Y/w9Px7k1yiog2RwVjAsCXAYOLFN0osXT7sdzB8iok+lf7hZF2wFzavp
      OqvY6WuAoItCwtsymVpGM+ewGoYPAgMBAAECgYEA1MLLrjKnWMZimR88EQjr0btP
      ODC6JmPsN7YzIFW30IAgY6GujRPHE7TWJx9jEqza4vDxz3cZ8OPztogUhM383UyL
      BWMX2FPFpxiRDYoqKSzaQ2/lSMdx+BBWmPet9IAMng0R5XnZyndUdWsXyf5yO9y3
      pugxrv9/pK2997BTEvkCQQD83ywqZu9NGAwMT68QjTpTQe/luwbKmlu33rhaELAG
      HO8dfhJnKlya67cCRBfrR6n1LPz/QllwletkR8SzjTZFAkEA+pN+3Oc64LtSjKH6
      iDLFgnWaY7hOdN2HlGpNVsL0NS/G1S1SCo8klFqP4ZKhn5/T732XU1qqg61WSrbb
      pSYqQwJBAKFbWxhXhJ2iGZYFhsU+CRi1e3oRRL0lkB8dDG/UNC5CakZceyu/eUYV
      4Tqd7tFgclATfAD5+o5/66uarCaSli0CQQDHkVlkzrTR799bKlbCys0LjmacLVov
      MZCd39wg0bx178tIVYQV7NORZF9bpNEctMqy3y/6rydHIHKtpt1gtvjJAkEAiu7B
      1TG32Z5O4mA39iSKMK3olzz6w4CZJ6nQbmKBwC9J2fuGVHH+OPUVEDkyFKYaZ4l2
      gOUBxZQFodH96U551Q==
      -----END PRIVATE KEY-----
      
  2. RSA加密解密工具类
    package com.yimen.data.test;
    
    import java.io.*;
    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 javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import org.bouncycastle.util.encoders.Base64;
    import sun.misc.BASE64Decoder;
    
    /**
     * 生成私钥:openssl genrsa -out rsa_private_key.pem 1024
     * 根据私钥生成公钥:openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
     * 私钥还不能直接被使用,需要进行PKCS#8编码:openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
     * sha1签名 openssl sha1 -sign rsa_private_key.pem -out rsasign.bin tos.txt
     * pkcs8_rsa_private_key 私钥
     * java可以使用
     */
    public class RSAEncrypt {
    
        /**
         * 字节数据转字符串专用集合
         */
        private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    
    
        /**
         * 随机生成密钥对
         * 生成公私钥的位置
         */
        public void genKeyPair(String filePath) {
            // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
            KeyPairGenerator keyPairGen = null;
            try {
                keyPairGen = KeyPairGenerator.getInstance("RSA");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            // 初始化密钥对生成器,密钥大小为96-1024位
            keyPairGen.initialize(1024, new SecureRandom());
            // 生成一个密钥对,保存在keyPair中
            KeyPair keyPair = keyPairGen.generateKeyPair();
            // 得到私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 得到公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    
            try {
                // 得到公钥字符串
               //Base64 base64 = new Base64();
                BASE64Encoder base64 = new BASE64Encoder();
                String publicKeyString = new String(base64.encode(publicKey.getEncoded()));
                // 得到私钥字符串
                String privateKeyString = new String(base64.encode(privateKey.getEncoded()));
                // 将密钥对写入到文件
                FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
                FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
                BufferedWriter pubbw = new BufferedWriter(pubfw);
                BufferedWriter pribw = new BufferedWriter(prifw);
                pubbw.write(publicKeyString);
                pribw.write(privateKeyString);
                pubbw.flush();
                pubbw.close();
                pubfw.close();
                pribw.flush();
                pribw.close();
                prifw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 从字符串中加载公钥
         *
         * @param publicKeyStr 公钥数据字符串
         * @throws Exception 加载公钥时产生的异常
         */
        public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
            try {
                BASE64Decoder base64Decoder = new BASE64Decoder();
                byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
                return (RSAPublicKey) keyFactory.generatePublic(keySpec);
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此算法");
            } catch (InvalidKeySpecException e) {
                throw new Exception("公钥非法");
            } catch (IOException e) {
                throw new Exception("公钥数据内容读取错误");
            } catch (NullPointerException e) {
                throw new Exception("公钥数据为空");
            }
        }
    
        /**
         * 从文件中输入流中加载公钥
         *
         * @param path
         *            公钥路径
         * @param flag
         *            true 为hdfs文件系统路径
         * @throws Exception
         *             加载公钥时产生的异常
         */
        public static String loadPublicKeyByFile(String path, boolean flag) throws Exception {
            try {
            	 BufferedReader br = null;
                if(flag){
                    Configuration conf = new Configuration();
                    FileSystem fs = FileSystem.get(conf);
                    FSDataInputStream in = fs.open(new Path(path));
                    br = new BufferedReader(new InputStreamReader(in));
                }else{
                    br = new BufferedReader(new FileReader(path));
                }
                String readLine = null;
                StringBuilder sb = new StringBuilder();
                while ((readLine = br.readLine()) != null) {
                    if (!readLine.contains("PUBLIC KEY")){
                        sb.append(readLine);
                    }
                }         
                br.close();
                return sb.toString();
            } catch (IOException e) {
                throw new Exception("公钥数据流读取错误");
            } catch (NullPointerException e) {
                throw new Exception("公钥输入流为空");
            }
        }
    
        /**
         * 从字符串中加载私钥
         *
         * @param privateKeyStr 私钥文件名
         * @return 是否成功
         * @throws Exception
         */
        public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
            try {
                BASE64Decoder base64Decoder = new BASE64Decoder();
                byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
                PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此算法");
            } catch (InvalidKeySpecException e) {
                throw new Exception("私钥非法");
            } catch (IOException e) {
                throw new Exception("私钥数据内容读取错误");
            } catch (NullPointerException e) {
                throw new Exception("私钥数据为空");
            }
        }
    
        /**
         * 从文件中加载私钥
         *
         * @param path
         *            私钥文件名
         * @param flag
         *            true 为hdfs文件系统路径
         * @return 是否成功
         * @throws Exception
         */
        public static String loadPrivateKeyByFile(String path, boolean flag) throws Exception {
            try {
                BufferedReader br = null;
                if(flag){
                    Configuration conf = new Configuration();
                    FileSystem fs = FileSystem.get(conf);
                    FSDataInputStream in = fs.open(new Path(path));
                    br = new BufferedReader(new InputStreamReader(in));
                }else{
                    br = new BufferedReader(new FileReader(path));
                }
                String readLine = null;
                StringBuilder sb = new StringBuilder();
                while ((readLine = br.readLine()) != null) {
                    if (!readLine.contains("PRIVATE KEY")){
                        sb.append(readLine);
                    }
                }
                br.close();
                return sb.toString();
            } catch (IOException e) {
                throw new Exception("私钥数据读取错误");
            } catch (NullPointerException e) {
                throw new Exception("私钥输入流为空");
            }
        }
    
    
        /**
         * 公钥加密
         *
         * @param publicKey     公钥
         * @param plainTextData 明文数据
         * @return
         * @throws Exception 加密过程中的异常信息
         */
        public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
                throws Exception {
            if (publicKey == null) {
                throw new Exception("加密公钥为空, 请设置");
            }
            Cipher cipher = null;
            try {
                // 使用默认RSA
                cipher = Cipher.getInstance("RSA");
                // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
                cipher.init(Cipher.ENCRYPT_MODE, publicKey);
                byte[] output = cipher.doFinal(plainTextData);
                return output;
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此加密算法");
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
                return null;
            } catch (InvalidKeyException e) {
                throw new Exception("加密公钥非法,请检查");
            } catch (IllegalBlockSizeException e) {
                throw new Exception("明文长度非法");
            } catch (BadPaddingException e) {
                throw new Exception("明文数据已损坏");
            }
        }
    
        /**
         * 公钥解密
         *
         * @param publicKey  公钥
         * @param cipherData 密文数据
         * @return 明文
         * @throws Exception 解密过程中的异常信息
         */
        public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
                throws Exception {
            if (publicKey == null) {
                throw new Exception("解密公钥为空, 请设置");
            }
            Cipher cipher = null;
            try {
                // 使用默认RSA
                cipher = Cipher.getInstance("RSA");
                // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
                cipher.init(Cipher.DECRYPT_MODE, publicKey);
                byte[] output = cipher.doFinal(cipherData);
                return output;
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此解密算法");
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
                return null;
            } catch (InvalidKeyException e) {
                throw new Exception("解密公钥非法,请检查");
            } catch (IllegalBlockSizeException e) {
                throw new Exception("密文长度非法");
            } catch (BadPaddingException e) {
                throw new Exception("密文数据已损坏");
            }
        }
    
        /**
         * 私钥加密
         *
         * @param privateKey    私钥
         * @param plainTextData 明文数据
         * @return
         * @throws Exception 加密过程中的异常信息
         */
        public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
                throws Exception {
            if (privateKey == null) {
                throw new Exception("加密私钥为空, 请设置");
            }
            Cipher cipher = null;
            try {
                // 使用默认RSA
                cipher = Cipher.getInstance("RSA");
                cipher.init(Cipher.ENCRYPT_MODE, privateKey);
                byte[] output = cipher.doFinal(plainTextData);
                return output;
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此加密算法");
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
                return null;
            } catch (InvalidKeyException e) {
                throw new Exception("加密私钥非法,请检查");
            } catch (IllegalBlockSizeException e) {
                throw new Exception("明文长度非法");
            } catch (BadPaddingException e) {
                throw new Exception("明文数据已损坏");
            }
        }
    
        /**
         * 私钥解密
         *
         * @param privateKey 私钥
         * @param cipherData 密文数据
         * @return 明文
         * @throws Exception 解密过程中的异常信息
         */
        public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
            if (privateKey == null) {
                throw new Exception("解密私钥为空, 请设置");
            }
            Cipher cipher = null;
            try {
                // 使用默认RSA
                cipher = Cipher.getInstance("RSA");
                // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                byte[] output = cipher.doFinal(cipherData);
                return output;
            } catch (NoSuchAlgorithmException e) {
                throw new Exception("无此解密算法");
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
                return null;
            } catch (InvalidKeyException e) {
                throw new Exception("解密私钥非法,请检查");
            } catch (IllegalBlockSizeException e) {
                throw new Exception("密文长度非法");
            } catch (BadPaddingException e) {
                throw new Exception("密文数据已损坏");
            }
        }
    
    
        /**
         * 字节数据转十六进制字符串
         *
         * @param data 输入数据
         * @return 十六进制内容
         */
        public static String byteArrayToString(byte[] data) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
                stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
                // 取出字节的低四位 作为索引得到相应的十六进制标识符
                stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
                if (i < data.length - 1) {
                    stringBuilder.append(' ');
                }
            }
            return stringBuilder.toString();
        }
    
        // btye转换hex函数
        public static String ByteToHex(byte[] byteArray) {
            StringBuffer StrBuff = new StringBuffer();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    StrBuff.append("0").append(
                            Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return StrBuff.toString();
        }
    
    
        /**
         * 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
         */
        public static byte[] readFileByBytes(String fileName) {
            File file = new File(fileName);
            InputStream in = null;
            byte[] txt = new byte[(int) file.length()];
            try {
                // 一次读一个字节
                in = new FileInputStream(file);
                int tempbyte;
                int i = 0;
    
                while ((tempbyte = in.read()) != -1) {
                    txt[i] = (byte) tempbyte;
                    i++;
                }
                in.close();
                return txt;
            } catch (IOException e) {
                e.printStackTrace();
                return txt;
            }
        }
    }
    

    如果私钥文件编码是PKCS#1格式,这种格式Java是支持的,增加如下代码:

    RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(priKeyData));
    RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent());
    KeyFactory keyFactory= KeyFactory.getInstance("RSA");
    PrivateKey priKey= keyFactory.generatePrivate(rsaPrivKeySpec);
    
  3. 签名及校验类
    package com.yimen.data.test;
    
    import java.security.KeyFactory;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * RSA签名验签类
     */
    public class RSASignature {
    
        /**
         * 签名算法
         */
        public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    
        /**
         * RSA签名
         *
         * @param content    待签名数据
         * @param privateKey 商户私钥
         * @param encode     字符集编码
         * @return 签名值
         */
        public static String sign(String content, String privateKey, String encode) {
            try {
                Base64 base64 = new Base64();
                PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));
    
                KeyFactory keyf = KeyFactory.getInstance("RSA");
                PrivateKey priKey = keyf.generatePrivate(priPKCS8);
    
                java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
    
                signature.initSign(priKey);
                signature.update(content.getBytes(encode));
    
                byte[] signed = signature.sign();
    
                return new String(base64.encode(signed));
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return null;
        }
    
        public static String sign(String content, String privateKey) {
            try {
                Base64 base64 = new Base64();
                PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));
                KeyFactory keyf = KeyFactory.getInstance("RSA");
                PrivateKey priKey = keyf.generatePrivate(priPKCS8);
                java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
                signature.initSign(priKey);
                signature.update(content.getBytes());
                byte[] signed = signature.sign();
                return new String(base64.encode(signed));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
        /**
         * RSA验签名检查
         *
         * @param content   待签名数据
         * @param sign      签名值
         * @param publicKey 分配给开发商公钥
         * @param encode    字符集编码
         * @return 布尔值
         */
        public static boolean doCheck(String content, String sign, String publicKey, String encode) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                Base64 base64 = new Base64();
                byte[] encodedKey = base64.decode(publicKey);
                PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
    
                java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
    
                signature.initVerify(pubKey);
                signature.update(content.getBytes(encode));
    
                boolean bverify = signature.verify(base64.decode(sign));
                return bverify;
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return false;
        }
    
        public static boolean doCheck(String content, String sign, String publicKey) {
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                Base64 base64 = new Base64();
                byte[] encodedKey = base64.decode(publicKey);
                PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
                java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
                signature.initVerify(pubKey);
                signature.update(content.getBytes());
    
                boolean bverify = signature.verify(base64.decode(sign));
                return bverify;
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    
    }
    
  4. 测试类
    package com.yimen.data.test;
    
    import org.apache.commons.codec.binary.Base64;
    
    public class MainTest {
    
        public static void main(String[] args) throws Exception {
            String filepath = "D://tmp//";
    
    //         RSAEncrypt.genKeyPair(filepath);
            //公钥
            String publicKeyStr = RSAEncrypt.loadPublicKeyByFile(filepath + "publicKey.keystore");
            // 私钥
            String privateKeyStr = RSAEncrypt.loadPrivateKeyByFile(filepath + "privateKey.keystore");
    
            Base64 base64 = new Base64();
            System.out.println("--------------公钥加密私钥解密过程-------------------");
            String plainText = "ihep_公钥加密私钥解密";
            // 公钥加密过程
    
            System.out.println(publicKeyStr);
            byte[] cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(publicKeyStr), plainText.getBytes());
            String cipher = new String(base64.encode(cipherData));
            // 私钥解密过程
    
            System.out.println(privateKeyStr);
            byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(privateKeyStr),
                    base64.decode(cipher));
            String restr = new String(res);
            System.out.println("原文:" + plainText);
            System.out.println("加密:" + cipher);
            System.out.println("解密:" + restr);
            System.out.println();
    
            System.out.println("--------------私钥加密公钥解密过程-------------------");
    
            plainText = "ihep_私钥加密公钥解密";
            // 私钥加密过程
            cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(privateKeyStr), plainText.getBytes());
            cipher = new String(base64.encode(cipherData));
            // 公钥解密过程
            res = RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(publicKeyStr), base64.decode(cipher));
            restr = new String(res);
            System.out.println("原文:" + plainText);
            System.out.println("加密:" + cipher);
            System.out.println("解密:" + restr);
            System.out.println();
    
            System.out.println("---------------私钥签名过程------------------");
            String content = "ihep_这是用于签名的原始数据";
            String signstr = RSASignature.sign(content, privateKeyStr);
            System.out.println("签名原串:" + content);
            System.out.println("签名串:" + signstr);
            System.out.println();
    
            System.out.println("---------------公钥校验签名------------------");
            System.out.println("签名原串:" + content);
            System.out.println("签名串:" + signstr);
    
            System.out.println("验签结果:" + RSASignature.doCheck(content, signstr, publicKeyStr));
            System.out.println();
    
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值