精华内容
下载资源
问答
  • 2019-11-15 10:50:15

    通过 .keystore密钥文件实现

    生成密钥文件 test2.keystore

    • ./keytool -genkeypair -v -alias test2 -dname “CN=test2,OU=Wenyao,O=RnD,L=Yangpu,ST=Shanghai,C=China” -keyalg RSA -keysize 2048 -keypass 123456 -keystore d:/test2.keystore -storepass 123456 -validity 99999 -storetype JCEKS
    
    import org.springframework.util.Base64Utils;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.security.KeyStore;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.cert.Certificate;
    import static org.springframework.http.converter.FormHttpMessageConverter.DEFAULT_CHARSET;
    
    /**
     * 通过已生成的密钥文件签名类
     * */
    public class SignatureByFile {
        /** 密钥路径及文件名称*/
        private String keyStoreFilePath = "D:/test2.keystore";
        /** 密钥库口令*/
        private String keyStorePass = "123456";
        /** 密钥库算法*/
        private String keyStoreType = "JCEKS";
        /** 密钥项别名*/
        private String keyAlias = "test2";
        /** 密钥口令*/
        private String keyPass = "123456";
        /** 签名算法 [SHA256withRSA/SHA1withRSA/MD5withRSA/MD2withRSA]*/
        private String algorithm = "SHA256withRSA";
    
        /** 获取公钥*/
        public PublicKey getPublicKey(final String keyAlias) throws Exception {
            /** 指定密钥库算法创建实例*/
            final KeyStore ks = KeyStore.getInstance(keyStoreType);
            /** 指定要读取的密钥库文件, 创建文件输入流*/
            final InputStream is = new FileInputStream(keyStoreFilePath);
            /** 载入密钥库文件输入流*/
            ks.load(is, keyStorePass.toCharArray());
            /** 生成证书(X.509标准)*/
            final Certificate cert = ks.getCertificate(keyAlias);
            /** 从证书中获取公钥部分*/
            final PublicKey publicKey = cert.getPublicKey();
            return publicKey;
        }
    
        /** 获取私钥*/
        public PrivateKey getPrivateKey(final String keyAlias, final String keyAliasPass) throws Exception {
            /** 指定密钥库算法创建实例*/
            final KeyStore ks = KeyStore.getInstance(keyStoreType);
            /** 指定要读取的密钥库文件, 创建文件输入流*/
            final InputStream is = new FileInputStream(keyStoreFilePath);
            /** 载入密钥库文件输入流*/
            ks.load(is, keyStorePass.toCharArray());
            /** 通过别名和密钥口令, 从已载入的密钥库获取私钥*/
            final PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, keyAliasPass.toCharArray());
            return privateKey;
        }
    
        /**
         * RSA签名
         *  @param plainText 源文本
         *  @return 签名
         **/
        public String sign(final String plainText) throws Exception {
            /** 获取私钥*/
            final PrivateKey privateKey = getPrivateKey(keyAlias, keyPass);
            /** 生成签名算法实例*/
            final Signature instance = Signature.getInstance(algorithm);
            instance.initSign(privateKey);
            instance.update(plainText.getBytes(DEFAULT_CHARSET));
            final byte[] signature = instance.sign();
            return Base64Utils.encodeToString(signature);
        }
    
        /**
         * RSA签名校验
         *  @param plainText 源文本
         *  @param signedText 签名
         *  @return 签名
         **/
        public boolean verify(final String plainText, final String signedText) throws Exception {
            /** 获取公钥*/
            final PublicKey publicKey = getPublicKey(keyAlias);
            /** 生成签名算法实例*/
            final Signature instance = Signature.getInstance(algorithm);
            instance.initVerify(publicKey);
            instance.update(plainText.getBytes(DEFAULT_CHARSET));
            final byte[] signature = Base64Utils.decodeFromString(signedText);
            return instance.verify(signature);
        }
    
    }
    
    

    相关使用

    
            final String data = "签名前数据";
            final SignatureByFile signature = new SignatureByFile();
            final String signedData = signature.sign(data);
            final boolean verify = signature.verify(data, signedData);
            System.out.println(signedData);
            System.out.println(verify);
    
    > M5hgiRY30fX7zSo5i+YRpAzpLR0i7dNX1qN8cwN6Sf9JtjoCaVXUywSOz1PC3w311jXtixPMfK3B1+2R7qUlOjTOWPFBiMBqUYy4f0xXLFQw9kMDK/WTtn+nbVezHgqxtBjFNC1/nttmH7PSxhY+SV2KzU+RzC0F2tGhWm0JQQpCZuVQQzVdikJL8NBY8vdqT9SuEpFSX++f2gAQVFyro92ntye/zTbqOFr/qAhXF03CN2jGlvp7ZEbxkxqcMLSHjeTGF0VfzrLgDVpsQdh4qb3dr+tgrs1rgBsVKKiRKmsus4J7YKrjWzcgd/DZAIEozoMnDT/GOonAphRKG6VDMA==
    > true
    
    

    通过密钥生成器实现

    
    import org.springframework.util.Base64Utils;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.Signature;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import static org.springframework.http.converter.FormHttpMessageConverter.DEFAULT_CHARSET;
    
    /**
     * RSA算法签名类
     * */
    public class SignatureByRSA {
        /** 签名算法 [SHA256withRSA/SHA1withRSA/MD5withRSA/MD2withRSA]*/
        private String algorithm = "MD5withRSA";
        /** 秘钥对实例*/
        private KeyPair keyPair;
    
        /**
         * RSA签名校验
         *  @param keyalg 密钥算法 [RSA]
         *  @param keySize 密钥位大小 [1024,2048]
         * */
        public SignatureByRSA(final String keyalg, final int keySize) throws Exception {
            final KeyPairGenerator pairGenerator = KeyPairGenerator.getInstance(keyalg);
            pairGenerator.initialize(keySize);
            /** 生成秘钥对实例*/
            keyPair = pairGenerator.generateKeyPair();
        }
    
        /** 获得 RSA公钥*/
        public RSAPublicKey getPublicKey() {
            return (RSAPublicKey) keyPair.getPublic();
        }
    
        /** 获得 RSA私钥*/
        public RSAPrivateKey getPrivateKey() {
            return (RSAPrivateKey) keyPair.getPrivate();
        }
    
        /**
         * RSA签名
         *  @param plainText 源文本
         *  @return 签名
         **/
        public String sign(final String plainText) throws Exception {
            /** 生成签名算法实例*/
            final Signature instance = Signature.getInstance(algorithm);
            instance.initSign(getPrivateKey());
            instance.update(plainText.getBytes(DEFAULT_CHARSET));
            final byte[] signature = instance.sign();
            return Base64Utils.encodeToString(signature);
        }
    
        /**
         * RSA签名校验
         *  @param plainText 源文本
         *  @param signedText 签名
         *  @return 签名
         **/
        public boolean verify(final String plainText, final String signedText) throws Exception {
            /** 生成签名算法实例*/
            final Signature instance = Signature.getInstance(algorithm);
            instance.initVerify(getPublicKey());
            instance.update(plainText.getBytes(DEFAULT_CHARSET));
            final byte[] signature = Base64Utils.decodeFromString(signedText);
            return instance.verify(signature);
        }
    
    }
    
    

    Byte数据转换成 Hex字符串

    
        public static String convertBytes2HexString(final byte[] data) {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                String s = Integer.toHexString(0xFF & data[i]);
                if (s.length() == 1){
                    sb.append(0).append(s);
                }else {
                    sb.append(s);
                }
            }
            return sb.toString();
        }
        
    

    相关使用

    
            final String data = "签名前数据";
            final SignatureByRSA signature = new SignatureByRSA("RSA", 2048);
            final String signedData = signature.sign(data);
            final boolean verify = signature.verify(data, signedData);
            System.out.println(convertBytes2HexString(signature.getPublicKey().getEncoded()));
            System.out.println(convertBytes2HexString(signature.getPrivateKey().getEncoded()));
            System.out.println(signedData);
            System.out.println(verify);
    
    > 30820122300d06092a864886f70d01010105000382010f003082010a0282010100a0830541f5d36f87f02b2b5b4da4717fc6a6f6466f73ac6df0a6f5ac58494632f4ca6b524c96a8086e4d92fa2db90f8b74a98e4d647530974c5bb050b7eb103b3f60a29a98511ed8c14a58ca2caffa20be79f961a91daabf6311f58a9c3cf4df065b6943eea139c41fd982fca0172f6e0500d0a0fae1ec9891d488d78fb476b09aa278f2128f6cf41d0548af9057a967bf0f91405de2564221129d1a7b56ac8c6366fa507166a5549fd80c5297bb9f73add9ff2fe4d91e9c2fb0c7119762ed0f1441d1786340b8550760a9f8a752bc134754432c2ded1f6cfd8ae2a3b8a6f6febac7fbbd8201c668cdbacbde740f61fd3d3bb56c359a4e68b17054074f23d8670203010001
    > 308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100a0830541f5d36f87f02b2b5b4da4717fc6a6f6466f73ac6df0a6f5ac58494632f4ca6b524c96a8086e4d92fa2db90f8b74a98e4d647530974c5bb050b7eb103b3f60a29a98511ed8c14a58ca2caffa20be79f961a91daabf6311f58a9c3cf4df065b6943eea139c41fd982fca0172f6e0500d0a0fae1ec9891d488d78fb476b09aa278f2128f6cf41d0548af9057a967bf0f91405de2564221129d1a7b56ac8c6366fa507166a5549fd80c5297bb9f73add9ff2fe4d91e9c2fb0c7119762ed0f1441d1786340b8550760a9f8a752bc134754432c2ded1f6cfd8ae2a3b8a6f6febac7fbbd8201c668cdbacbde740f61fd3d3bb56c359a4e68b17054074f23d86702030100010282010021f5d6a4f007fe2efac78772d7e89502fddad17c71943dc53d07762f32b6be1d85e155f7a1b0b678a22dd38d0f237a807cfc6ad94109f26ff07dedbe064bbbb16d655ac1eebc2b149d40c7ac6eec04b5ecd70dc675eb8af6d7553368524a2b5d0c9146a252d8d5ca031b1835af0178cd844d79d6b57e1b7ae44fdd6c0e419662ccc1d12d019e0ca5c89b336e06a316807bdf0fd490587ed2064456c4052179b896a1943be20c3badb49670a296672b70016c1a5cae9ab09caf46a4c189cb2ceb951347ff014f865fe027e529b9f3be6768fda01c0cb969e341302b64d6bab1f06e433cbd044d92e3c1a2d29209679964ce0d9effb7a845e660631c937b060a9102818100e5b60a8d6b16f7710eb8685096c19614feedcb81ea5923025c160b7d34decc4f67310185d813d23911bc96b9b53b2f8cf2ed82d31063e718649a760f41d6e42868e57545821c1734af883e010cf297247b114ec37bc06ef002943acbda9cc97fa57e6151d594b399dd31da14cf962ce713ff3c5fe4b7b03019fa5a3e0dcb3de502818100b2e19d0d0dc512bdb4d02e390d48960b8d7146f36f6aefeced4d4478c22d03769e4ece695ede8da73332125c74e0557a735c850ff8b15850cd5a1c211e8d7fa32bbb885b0792732108f0f3d21a8d2f9ea52d09b879a70c0cac075f3184c39a1bc9db2dee41ec841b2e010ea5a425da6db8595d969660c2f30519a553fd43f85b0281806cccf168941d77abcbfe1a2279954d81ba51653fae80f3ad0d72bf94593361f005ff572a4ef2ec726d6d36b2d51d2863893867eb926acf2d65912774088a40dcc6fa4fb6516efeaaccad2a391329dfdebe8faf0fb610aa3af1edc57f82971a75642c5cea06d07cd4d6c8e2f352735de74138761f3154b395c4e8285015f67ae50281810098724611d5e659ee6aa5f07e969f81a01ecea714d7a35f0d9fbef5d7a444106b8ac6c68a6e5b648555d01a6dc8fd565ba0ecfc497c3c4773b54e5222b793076fdbd95a7f9998699d81ad375d9b5b2f761876a58e1dbf0b39d17206e280aee22b44801248b6ce0657d380fb269719db691e6eaa9fa7509753dcc8da6915b253790281800f5db934ef6397c6081583ba35732fd8808fd9d955debbb3cfd013dde14c4bdef29dbe8577c865f7c6fb2696c55a44edef90a89b6c35969154376898dd120224218885070fb26d300837c34335052723cf44ab3d609f8ccc7430eb1e1e6e44028aa26d334c48ba426cef2cb1f78125fbe681e62f27dba8544cd9c9b2d838bef9
    hoJghoDi0WDNDcmsEyED1LNoaRTnZRD439v8tBlUimeKuBezrVH7fS7iTqyyCgBc+X6cdgk4pMo7eIMEBt+JwqBlKhjpdJZXQUHSbZQG7D+MGSXk9Ip5/FCIf3Y2NBc3Y5dHiqYVy0vQ5QClj8QK0l8hPZKUuvXSHHWNo72tF7OHkqdy/gysmVRbul3Kyt/QqA7CVU4d9IkNOoePlvqYcZeAdx2yIDisS0jR+RnsrKM2UuRrRJRMaPpRcxtYz/tqnvr/x4ZeUvLT85XZZAf9pL/Me2XwmN3D5i7tyuKKG/bftMS65YOyNvFD0Kytd9fAoOaeMVilfos9R4C3rjSh1w==
    > true
    
    

    如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!

    更多相关内容
  • RSA电子签名Jmeter脚本文件,含响应信息unicode转中文。
  • 支付宝rsa签名验签工具,包含使用说明和源码实现 1、双击脚本文件 “RSA签名验签工具.bat” 即运行RSA签名验签工具。 2、RSA2签名方式使用算法:SHA256withRSA。 RSA签名方式使用算法:SHA1withRSA。 3、签名验签...
  • 标准RSA签名验签工具

    2018-12-14 16:31:30
    delphi标准RSA签名验签工具,方便测试RSA的签名和验证与其他语言之间的签名正确性
  • AES RSA 加密解密工具类以及RSA 签名 和验证签名等方法以及自动生成成对的RSA 公私钥
  • RSA签名验签工具

    2018-01-26 14:43:05
    支付宝最新版的签名验签工具 支持RSA RSA2 MD5 ,生成 效验秘钥等
  • 1、双击脚本文件 “RSA签名验签工具.bat” 即运行RSA签名验签工具。 2、RSA2签名方式使用算法:SHA256withRSA。 RSA签名方式使用算法:SHA1withRSA。 3、签名验签工具不要放在文件路径名存在空格的文件夹下。
  • 支付宝官方RSA256签名工具,可生成1024,2048等长度密钥,也可以校验公私钥的匹配性
  • 【小程序】RSA签名

    2021-03-29 21:32:30
    title: 【小程序】RSA签名type: categoriesdate: 2017-05-27 17:01:15categories: 小程序tags: 一个适用于微信小程序的RSA签名库。RSA签名的小程序DEMO:...
  • rsa签名校验工具

    2018-05-21 10:34:44
    RAS签名校验工具,本地生成公钥私钥,快速便捷的接入支付宝支付系统
  • 1、包含delphi7实现 rsa1,与rsa256的源码,及DLL,函数如下 // ftemp 待加密字符串,,fkeyfile 密钥文件路径, ftype 加密类型 1 rsa1 ,2 rsa256 function GetRSA(Ftemp:PChar;FkeyFile:PChar;Ftype:PChar):...
  • 参数签名生成及校验
  • RSA签名工具类

    2017-03-17 18:28:46
    RSA签名工具类
  • rsa签名Net 与JAVA对接

    2018-04-24 09:18:00
    与蘑菇对接时用到,Java rsa 公私钥对转,及细节处理 与蘑菇对接时用到,Java rsa 公私钥对转,及细节处理
  • 本资源包含:RSA签名算法,格式为PKCS7。RSA签名算法,格式为PKCS7。RSA签名算法,格式为PKCS7。RSA签名算法,格式为PKCS7。 RSA加密算法是一种非对称加密算法。在公开密钥加密和电子商业中RSA被广泛使用。RSA是1977...
  • JS RSA 签名 加密

    2018-04-17 15:15:08
    JS RSA 签名 加密
  • 该系统采用了独立的RSA算法确保了办公过程中公文流转的真实性和有效性。  1 RSA算法及数字证书  1.1 RSA 算法简介  (1)密钥的生成  密钥的生成过程:  ①选择两个大素数p,q,(p,q 为互异素数,需要...
  • RSA签名算法

    千次阅读 2022-01-24 14:44:53
    /** * @author kyrie * @Description: Java实现RSA签名算法 * @date 2022/1/24 13:54 */ public class RSACoder { //非对称加密算法 public static final String KEY_ALGORITHM = "RSA"; //数字签名 签名/验证算法 ...

    一、加密算法分类

    1、密钥

            密钥,一般就是一个字符串或数字,在加密或者解密时传递给加密或解密算法,以使算法能够正确对明文加密或者对密文解密。

    2、加密算法分类

            大体上分为单向加密和双向加密。

            2.1、单向加密

                    单向加密就是非可逆加密,就是不可解密的加密方法,由于其在加密后会生成唯一的加密串,故而经常用于检测数据传输过程中是否被修改。常见的单向加密有MD5、SHA、HMAC。我们只是把他们作为加密的基础,单纯的以上三种加密并不可靠。

            2.2、双向加密

                    双向加密又可以分为对称加密和非对称加密。如果你想进行加解密操作的时候需要具备两样东西:密钥和加解密算法。

            2.3、对称加密

                    对称加密算法的特点是加密使用的密钥和解密使用的密钥是相同的。也就是说,加密和解密都是使用的同一个密钥。因此对称加密算法要保证安全性的话,密钥自然要做好保密,只能让使用的人知道,不能对外公开。

            2.4、非对称加密

                    在非对称加密算法中,有公钥的私钥两种密钥,其中 ,公钥是公开的,不需要保密,私钥由个人持有,必须妥善保管和注意保密。加密和解密使用两种不同的密钥,是它得名的原因。常见的、应用很广的非对称加密算法:RSA。

    二、RSA

    1、RSA加密算法是一种非对称加密算法,所谓非对称,就是指该算法需要一对密钥,使用其中一个加密,则需要用另一个才能解密。这样就可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数字相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。通常个人保存私钥,公钥是公开的(可能同时多人持有)。

    2、RSA加密、签名区别

    加密和签名都是为了安全性考虑,但略有不同。常有人问加密和签名是用私钥还是公钥?其实都是对加密和签名的作用有所混淆。简单的说,加密是为了防止信息被泄露,而签名是为了防止信息被篡改。这里举两个例子说明:

            第一个场景:战场上,B要给A传递一条信息,内容指令为:坚守阵地!

            RSA的加密过程如下:

            (1)A生成一对密钥(公钥和私钥),私钥不公开,A自己保留;公钥为公开的,任何人可以获取。

            (2)A传递自己的公钥给B,B用A的公钥对消息进行加密。

            (3)A接收到B的加密信息,利用A自己的私钥对消息进行解密。

            在这个过程中,只有两次传递过程,第一次是A传递公钥给B,第二次是B传递加密信息给A,即使敌方截获,也没有危险性,因为只有A的私钥才能对消息进行解密,防止了消息内容的泄露。

            第二个场景:A收到B发的加密信息后,需要进行回复“收到”。

            RSA的签名过程如下:

            (1)A生成一对密钥(公钥和私钥),私钥不公开,A自己保留;公钥为公开的,任何人可以获取。

            (2)A用自己的私钥对消息加签,形成签名,并将加签的消息和消息本身一起传递给B。

            (3)B收到消息后,再获取A的公钥进行验签,如果验签出来的内容与消息本身一致,证明消息是A回复的。

            在这个过程中,只有两次传递过程,第一次是A传递加签的消息和消息本身给B,第二次是B获取A的公钥,即使都被敌方截获,也没有危险性,因为只有A的私钥才能对消息进行签名,即使知道了消息内容,也无法伪造带签名的回复给B,防止了消息内容的篡改。

            但是,综合两个场景会发现。第一个场景虽然被截获的消息没有泄露,但是可以利用截获的公钥,将假指令进行加密,然后传递给A。第二个场景虽然截获的消息不能被篡改,但是消息的内容可以利用公钥验签来获得,并不能防止被泄露。所以在实际应用中,要根据具体情况使用,也可以同时使用加密和签名,比如A和B都有一套自己的公钥和私钥,当A要给B发送消息时,先用B的公钥对消息加密,再对加密的消息使用A的私钥加签名,达到既不泄露也不被篡改,更能保证消息的安全性

            总结:公钥加密、私钥解密、私钥签名、公钥验签。

    三、Java中RSA签名算法实现

    package cn.csdn.rsa;
    
    import org.apache.commons.codec.DecoderException;
    import org.apache.commons.codec.binary.Hex;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    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;
    
    /**
     * @author kyrie
     * @Description: Java实现RSA签名算法
     * @date 2022/1/24 13:54
     */
    
    public class RSACoder {
        //非对称加密算法
        public static final String KEY_ALGORITHM = "RSA";
        //数字签名 签名/验证算法
        public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
        //公钥
        private static final String PUBLIC_KEY = "RSAPublicKey";
        //私钥
        private static final String PRIVATE_KEY = "RSAPrivateKey";
        //RSA密钥长度默认1024位,密钥长度必须是64的倍数,范围在512-65536位之间
        private static final int KEY_SIZE = 512;
    
        /**
         * 私钥解密
         */
        public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            //取得私钥
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成私钥
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            //对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 公钥解密
         */
        public static byte[] decryptByPublicKey(byte[] data, byte[] key)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            //取得公钥
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成公钥
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            //对数据解密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 公钥加密
         */
        public static byte[] encryptByPublicKey(byte[] data, byte[] key)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            //取得公钥
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成公钥
            PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
            //对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(data);
        }
    
    
        /**
         * 私钥加密
         */
        public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            //取得私钥
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成私钥
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            //对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            return cipher.doFinal(data);
        }
    
        /**
         * 取得私钥
         */
        public static byte[] getPrivateKey(Map<String, Object> keyMap)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            return key.getEncoded();
        }
    
        /**
         * 取得公钥
         */
        public static byte[] getPublicKey(Map<String, Object> keyMap)
                throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
            Key key = (Key) keyMap.get(PUBLIC_KEY);
            return key.getEncoded();
        }
    
        /**
         * 初始化密钥
         */
        public static Map<String, Object> initKey() throws NoSuchAlgorithmException {
            //实例化密钥生成器
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            //初始化密钥对生成器
            keyPairGenerator.initialize(KEY_SIZE);
            //生成密钥对
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            //公钥
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            //私钥
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            //封装密钥
            Map<String, Object> keyMap = new HashMap<>();
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }
    
        /**
         * 签名
         *
         * @param data       待签名数据
         * @param privateKey 私钥
         * @return 数字签名
         */
        public static byte[] sign(byte[] data, byte[] privateKey)
                throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
            //转换私钥材料
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey);
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //取私钥对象
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            //实例化Signature
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            //初始化Signature
            signature.initSign(priKey);
            //更新
            signature.update(data);
            //签名
            return signature.sign();
        }
    
        /**
         * 公钥校验
         *
         * @param data      待校验数据
         * @param publicKey 公钥
         * @param sign      数字签名
         * @return 校验成功返回true 失败返回false
         */
        public static boolean verify(byte[] data, byte[] publicKey, byte[] sign)
                throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
            //转换公钥材料
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
            //实例化密钥工厂
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            //生成公钥
            PublicKey pubKey = keyFactory.generatePublic(keySpec);
            //实例化Signature
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            //初始化Signature
            signature.initVerify(pubKey);
            //更新
            signature.update(data);
            //验证
            return signature.verify(sign);
        }
    
        /**
         * 私钥签名
         *
         * @param data       待签名数据
         * @param privateKey 私钥
         * @return 十六进行签名字符串
         */
        public static String sign(byte[] data, String privateKey)
                throws DecoderException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
            byte[] sign = sign(data, getKey(privateKey));
            return Hex.encodeHexString(sign);
        }
    
    
        /**
         * 公钥校验
         *
         * @param data      待校验数据
         * @param publicKey 公钥
         * @param sign      签名
         * @return 成功返回true,失败返回false
         */
        public static boolean verify(byte[] data, String publicKey, String sign)
                throws DecoderException, InvalidKeySpecException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
            return verify(data, getKey(publicKey), Hex.decodeHex(sign.toCharArray()));
        }
    
    
        /**
         * 私钥加密
         */
        public static byte[] encryptByPrivateKey(byte[] data, String key)
                throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
            return encryptByPrivateKey(data, getKey(key));
        }
    
        /**
         * 公钥加密
         */
        public static byte[] encryptByPublicKey(byte[] data, String key)
                throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
            return encryptByPublicKey(data, getKey(key));
        }
    
        /**
         * 私钥解密
         */
        public static byte[] decryptByPrivateKey(byte[] data, String key)
                throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
            return decryptByPrivateKey(data, getKey(key));
        }
    
        /**
         * 公钥解密
         */
        public static byte[] decryptByPublicKey(byte[] data, String key)
                throws DecoderException, NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
            return decryptByPublicKey(data, getKey(key));
        }
    
        /**
         * 初始化密钥
         *
         * @return 十六进制编码密钥
         */
        public static String getPrivateKeyString(Map<String, Object> keyMap)
                throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    //    return Base64.encodeBase64String(getPrivateKey(keyMap));
            return Hex.encodeHexString(getPrivateKey(keyMap));
        }
    
        /**
         * 初始化密钥
         *
         * @return 十六进制编码密钥
         */
        public static String getPublicKeyString(Map<String, Object> keyMap)
                throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidKeySpecException {
    //    return Base64.encodeBase64String(getPublicKey(keyMap));
            return Hex.encodeHexString(getPublicKey(keyMap));
        }
    
        /**
         * 获取密钥
         *
         * @param key 密钥
         * @return 密钥
         */
        public static byte[] getKey(String key) throws DecoderException {
            return Hex.decodeHex(key.toCharArray());
    //    return Base64.decodeBase64(key);
        }
    
    
        public static void main(String[] args)
                throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException, InvalidKeySpecException, NoSuchPaddingException, DecoderException, SignatureException {
            Map<String, Object> keyMap = RSACoder.initKey();
    
            //获取并打印公钥
            String publicKey = RSACoder.getPublicKeyString(keyMap);
            System.out.println("publicKey=" + publicKey);
            //获取并打印私钥
            String privateKey = RSACoder.getPrivateKeyString(keyMap);
            System.out.println("privateKey=" + privateKey);
    
            // 公钥加密、私钥解密
            String inputStr = "有内鬼终止交易,密文代码:001002003007";
            byte[] data = inputStr.getBytes();
            System.out.println("原文:" + inputStr);
            byte[] encodeData = RSACoder.encryptByPublicKey(data, publicKey);
            System.out.println("加密后:" + Hex.encodeHexString(encodeData));
            byte[] decodeData = RSACoder.decryptByPrivateKey(encodeData, privateKey);
            System.out.println("解密后:" + new String(decodeData));
            //私钥签名、公钥校验
            String sign = RSACoder.sign(data, privateKey);
            System.out.println("签名后:" + sign);
            System.out.println("校验=" + RSACoder.verify(data, publicKey, sign));
        }
    
    }
    

     代码原文:JAVA中RSA签名算法实现 - 兵阳的个人页面 - OSCHINA - 中文开源技术交流社区

    青年人的责任重大!努力吧...

    展开全文
  • Android RSA 签名工具类

    2015-09-01 16:21:30
    文件来自支付宝客户端 Demo,用于使用相应的私钥加密某段密文
  • 支付宝RSA签名验签工具windows_V1.4,官网下载的验签工具,需要的小伙伴下载吧
  • 主要介绍了PHP实现的MD5结合RSA签名算法,结合实例形式分析了php使用md5结合RSA实现的签名算法相关操作技巧,并附带了RSA公钥与私钥的相关说明,需要的朋友可以参考下
  • RSA签名验签工具windows

    2018-05-22 15:49:00
    非常好用的rsa工具,可以生成公钥私钥字符串,也可以生成文件,也可以直接在工具中做加签和验签的动作,可以验证公钥私钥是否是一对儿,也可以从私钥中直接获取公钥,功能很强大
  • RSA签名验证示例源码

    2017-12-30 18:35:24
    基于OpenSSL实现RSA签名与验证流程,使用了RSA_NO_PADDING mode
  • 本文实例讲述了C#自定义RSA加密解密及RSA签名和验证类。分享给大家供大家参考。具体分析如下: 这个C#类自定义RSA加密解密及RSA签名和验证,包含了RSA加密、解密及签名所需的相关函数,带有详细的注释说明。 using ...
  • Java 实现RSA 签名/验签与加密解密

    千次阅读 2021-11-04 15:53:26
    RSA 算法相比于AES算法不同的是RSA的秘钥为不同的两个一个为公钥一个为私钥且目前理论上无法通过私钥/公钥去推得公钥/私钥。其数学原理为数论中寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,将...

    一、前言

    RSA 算法相比于AES算法不同的是RSA的秘钥为不同的两个一个为公钥一个为私钥且目前理论上无法通过私钥/公钥去推得公钥/私钥。其数学原理为数论中寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其困难,将他们的乘积作为公钥,从而无法通过分解因式获得私钥实现。
    一般情况下,使用私钥进行签名,使用公钥验证签名。签名验签是为了验证用户身份是否合法,和登录一个作用。用于被调用方验证;使用公钥进行加密使用私钥解密.。加密解密是为防止数据被篡改。
    相比于AES来说RSA一般用于加密短的明文,因为内容越长,效率越低。

    二、签名与验签

    1、程序代码如下:

    package cn.zlc.des.rsa;
    
    import java.nio.charset.StandardCharsets;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;
    import javax.crypto.Cipher;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * @author Jacob
     * @version 1.0
     * @date 2021/11/4 15:57
     */
    @Slf4j
    public class RSAUtil {
    
      public static final String KEY_ALGORITHM = "RSA";
      public static final String PUBLIC_KEY = "publicKey";
      public static final String PRIVATE_KEY = "privateKey";
    
      //map对象中存放公私钥
      public static Map<String, Key> initKey() throws Exception {
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();
        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公私钥对象存入map中
        Map<String, Key> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
      }
    
      /**
       * 从公钥字符串中获取公钥
       * @param key Base64的公钥字符串
       * @return 公钥
       * @throws Exception 异常
       */
      public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
      }
    
      /**
       * 从私钥字符串中获取私钥
       * @param key Base64的私钥字符串
       * @return 私钥
       * @throws Exception 异常
       */
      public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(StandardCharsets.UTF_8));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
      }
    
      /**
       * RSA私钥签名
       * @param content 待签名数据
       * @param privateKey 私钥
       * @return 签名值
       */
      public static String signByPrivateKey(String content, String privateKey) {
        try {
          PrivateKey priKey = getPrivateKey(privateKey);
          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initSign(priKey);
          signature.update(content.getBytes(StandardCharsets.UTF_8));
          byte[] signed = signature.sign();
          return new String(Base64.encodeBase64URLSafe(signed), StandardCharsets.UTF_8);
        } catch (Exception e) {
          log.warn("sign error, content: {}, priKey: {}", content, privateKey);
          log.error("sign error, message is {}", e.getMessage());
        }
        return null;
      }
    
      /**
       * 通过公钥验签
       * @param content 验签内容
       * @param sign  签名
       * @param publicKey 公钥
       * @return 验签结果
       */
      public static boolean verifySignByPublicKey(String content, String sign, String publicKey) {
        try {
          PublicKey pubKey = getPublicKey(publicKey);
          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initVerify(pubKey);
          signature.update(content.getBytes(StandardCharsets.UTF_8));
          return signature.verify(Base64.decodeBase64(sign.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
          log.warn("sign error, content: {}, sign: {}, pubKey: {}", content, sign, publicKey);
          log.error("sign error", e);
        }
        return false;
      }
    
      public static void main(String[] args) {
        String signContent = "待签名数据";
        // 第一步,生成一对公私钥
        Map<String, Key> keys = new HashMap<>(2);
        try {
         keys = RSAUtil.initKey();
        }catch (Exception e){
          log.error("init RSA key error,message is {}", e.getMessage());
          System.exit(-1);
        }
        // 获得私钥
        Key privateKey = keys.get(PRIVATE_KEY);
        // 私钥Base64编码字符串
        String base64PrivateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
        log.info("base64 privateKey String is:{}", base64PrivateKeyStr);
        // 签名
        String signString = RSAUtil.signByPrivateKey(signContent, base64PrivateKeyStr);
        log.info("sign by privateKey ,signString is: {}", signString);
        // 获得公钥
        Key publicKey = keys.get(PUBLIC_KEY);
        String base64PublicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());
        log.info("base64 publicKey String is:{}", base64PublicKeyStr);
        boolean verifySignResult = RSAUtil.verifySignByPublicKey(signContent ,signString, base64PublicKeyStr);
        log.info("verify sign result is: {}", verifySignResult);
      }
    }
    
    
    

    2、程序运行结果:

    17:57:52.337 [main] INFO cn.zlc.des.rsa.RSAUtil - base64 privateKey String is:MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAInvHaqkXciGW5sFb9S2oF/2KYR7zm+IGfX/KIUlMoo/g5v5DZBBFRr4Ez+PUvsjvnCigwHhigD6QCs2bTPuQfUdqeUV3N5qcf1wHjxA0mERrVneAuR1dyhikB2RbRkw901ZIpYEKBh5LDNEiA1wAkYvw9cpl6i31uiISPhmvpoXAgMBAAECgYAUUHcaDqMRSVhseFyEA3GTMHnk3ScGHhFUvYOGOHg9DCWh7wgkWrF1C1wqXD1oZ1dA125b9I+SnUieFKH4p/pmm9XvQZ3pwz2rJd+PFdo3KpXtdH6snJn4X1dO/1E8uaJOVKyKqZmNYO7/TK+4SxPKsR7W1em1wtvXTMy6/jK84QJBAMPWULhZyw4YYQNNl9YhAP+T3bJLyI1zl1xXmg1JB34GrkReh/otw8Mc9rDTkf8wjUwYtPUyC7q3tibTdu1o0VMCQQC0Tv0XCTE/ghMndxM+16XAfFyY4WkN7Se/Cp62UPHmvQ/HIusvGrdPkI59Bv7rq+gTebImzXxnRwe29+X4tKetAkBIgWiRWG1dYplIZ8n3dXCxL0W9ZWFzPYCkp6pZkNg9SKvslDMz5Q29h1OuVCaRnKAztFILFeRR1QKTjWdSrqQRAkA+kaJ12fTDCwpGiaWeCwszrnQbgS0JbiB6xN6qeZBX94eAHPfr0qOF8q3faQwREAhqqbJOkMP4usdMkN223knJAkBW8PO+DilQFgRqH47RIhz3md0EKVzqE02aYb8XO4DMQ8UgOqX6YGp3KEWW7Gwb0ASQZLlW+wkFmgLtt4aGhNY/
    17:57:52.346 [main] INFO cn.zlc.des.rsa.RSAUtil - sign by privateKey ,signString is: F1agu3KpQtcxXMFwiRNUv5LA-A9ebellLL_RnwoqxRQTwI5mt8bHq3tMzZxUq0E9Odaa-88oVnq9t1X9G9PoiVDcaMLXIrWCvDMw3xdssZ-TbspteBO1sGdV9UOk58KLU3aft3R3HvCaYl0mXcybdrN--MRtnB5xJYfHyh8QwL8
    17:57:52.346 [main] INFO cn.zlc.des.rsa.RSAUtil - base64 publicKey String is:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJ7x2qpF3IhlubBW/UtqBf9imEe85viBn1/yiFJTKKP4Ob+Q2QQRUa+BM/j1L7I75wooMB4YoA+kArNm0z7kH1HanlFdzeanH9cB48QNJhEa1Z3gLkdXcoYpAdkW0ZMPdNWSKWBCgYeSwzRIgNcAJGL8PXKZeot9boiEj4Zr6aFwIDAQAB
    17:57:52.347 [main] INFO cn.zlc.des.rsa.RSAUtil - verify sign result is: true
    

    三、加密解密

    1、添加加解密方法

    package cn.zlc.des.rsa;
    
    import java.nio.charset.StandardCharsets;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;
    import javax.crypto.Cipher;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.codec.binary.Base64;
    
    /**
     * @author Jacob
     * @version 1.0
     * @date 2021/11/4 15:57
     */
    @Slf4j
    public class RSAUtil {
    
      public static final String KEY_ALGORITHM = "RSA";
      public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
      public static final String PUBLIC_KEY = "publicKey";
      public static final String PRIVATE_KEY = "privateKey";
    
      //map对象中存放公私钥
      public static Map<String, Key> initKey() throws Exception {
        //获得对象 KeyPairGenerator 参数 RSA 1024个字节
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        //通过对象 KeyPairGenerator 获取对象KeyPair
        KeyPair keyPair = keyPairGen.generateKeyPair();
        //通过对象 KeyPair 获取RSA公私钥对象RSAPublicKey RSAPrivateKey
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //公私钥对象存入map中
        Map<String, Key> keyMap = new HashMap<>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
      }
    
      /**
       * 从公钥字符串中获取公钥
       * @param key Base64的公钥字符串
       * @return 公钥
       * @throws Exception 异常
       */
      public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(keySpec);
      }
    
      /**
       * 从私钥字符串中获取私钥
       * @param key Base64的私钥字符串
       * @return 私钥
       * @throws Exception 异常
       */
      public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(StandardCharsets.UTF_8));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
      }
    
      /**
       * RSA私钥签名
       * @param content 待签名数据
       * @param privateKey 私钥
       * @return 签名值
       */
      public static String signByPrivateKey(String content, String privateKey) {
        try {
          PrivateKey priKey = getPrivateKey(privateKey);
          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initSign(priKey);
          signature.update(content.getBytes(StandardCharsets.UTF_8));
          byte[] signed = signature.sign();
          return new String(Base64.encodeBase64URLSafe(signed), StandardCharsets.UTF_8);
        } catch (Exception e) {
          log.warn("sign error, content: {}, priKey: {}", content, privateKey);
          log.error("sign error, message is {}", e.getMessage());
        }
        return null;
      }
    
      /**
       * 通过公钥验签
       * @param content 验签内容
       * @param sign  签名
       * @param publicKey 公钥
       * @return 验签结果
       */
      public static boolean verifySignByPublicKey(String content, String sign, String publicKey) {
        try {
          PublicKey pubKey = getPublicKey(publicKey);
          Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
          signature.initVerify(pubKey);
          signature.update(content.getBytes(StandardCharsets.UTF_8));
          return signature.verify(Base64.decodeBase64(sign.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
          log.warn("sign error, content: {}, sign: {}, pubKey: {}", content, sign, publicKey);
          log.error("sign error", e);
        }
        return false;
      }
    
      /**
       * 通过公钥加密
       * @param plainText 明文
       * @param publicKey 公钥
       * @return 密文
       */
      public static String encryptByPublicKey(String plainText, String publicKey) {
        try {
          PublicKey pubKey = getPublicKey(publicKey);
          Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
          cipher.init(Cipher.ENCRYPT_MODE, pubKey);
          byte[] enBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
          return Base64.encodeBase64String(enBytes);
        } catch (Exception e) {
          log.error("encrypt error", e);
        }
        return null;
      }
    
      /**
       * 通过私钥解密
       * @param enStr 加密字符串
       * @param privateKey 私钥
       * @return 明文
       */
      public static String decryptByPrivateKey(String enStr, String privateKey) {
        try {
          PrivateKey priKey = getPrivateKey(privateKey);
          Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
          cipher.init(Cipher.DECRYPT_MODE, priKey);
          byte[] deBytes = cipher.doFinal(Base64.decodeBase64(enStr));
          return new String(deBytes);
        } catch (Exception e) {
          log.error("decrypt error", e);
        }
        return null;
      }
    
      public static void main(String[] args) {
        String encryptionContent = "待加密数据";
        // 第一步,生成一对公私钥
        Map<String, Key> keys = new HashMap<>(2);
        try {
         keys = RSAUtil.initKey();
        }catch (Exception e){
          log.error("init RSA key error,message is {}", e.getMessage());
          System.exit(-1);
        }
        // 获得公钥
        Key publicKey = keys.get(PUBLIC_KEY);
        String base64PublicKeyStr = Base64.encodeBase64String(publicKey.getEncoded());
        log.info("base64 publicKey String is:{}", base64PublicKeyStr);
        // 加密
        String encryptionString = RSAUtil.encryptByPublicKey(encryptionContent, base64PublicKeyStr);
        log.info("encryptionString by publicKey ,encryptionString is: {}", encryptionString);
        // 解密
        // 获得私钥
        Key privateKey = keys.get(PRIVATE_KEY);
        // 私钥Base64编码字符串
        String base64PrivateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
        log.info("base64 privateKey String is:{}", base64PrivateKeyStr);
        String decryptionString = RSAUtil.decryptByPrivateKey(encryptionString, base64PrivateKeyStr);
        log.info("decryptionString by privateKey ,decryptionString is: {}", decryptionString);
      }
    }
    
    

    2、程序运行结果

    18:30:52.140 [main] INFO cn.zlc.des.rsa.RSAUtil - base64 publicKey String is:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCU9l+2w68GDlSxNZQK5BaU+DvcKAAOfHLTJE3KYSOA+vucvoEGgmZ8rsULoI/s0nrsqtI/s/D0VS0vDTLpv/EFWAwAZquhrB6RNyAxjgzgugNbC9oxThEyOAD5VztM0p4XmR8ynK7OeD/BkNjSPVAeZLRfxZKsBGx846OhepX8swIDAQAB
    18:30:52.331 [main] INFO cn.zlc.des.rsa.RSAUtil - encryptionString by publicKey ,encryptionString is: icurdQyGP2JpI2q+BRf6MgnEk4or1Fdlpxyjr7/yTXVLNHgM7fcNKFcSO/s7EORJEwN1Z96sYOi7kU74fITSo92jsyem4yUajeHzbElJ7dy/fIAkyFwJibxfyaalY897NtJToFrT5eqk8LKkoUwSjfRo/SM/APkO4a1+oIs0zWA=
    18:30:52.331 [main] INFO cn.zlc.des.rsa.RSAUtil - base64 privateKey String is:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJT2X7bDrwYOVLE1lArkFpT4O9woAA58ctMkTcphI4D6+5y+gQaCZnyuxQugj+zSeuyq0j+z8PRVLS8NMum/8QVYDABmq6GsHpE3IDGODOC6A1sL2jFOETI4APlXO0zSnheZHzKcrs54P8GQ2NI9UB5ktF/FkqwEbHzjo6F6lfyzAgMBAAECgYAtyLfMZcKyus7fFJem7UnfiZhkZ0r1KNzl9n+OV2LhLsMM/ySLCqNTaSgZFcWGxX6QpUQv3i+N+WwEzSq724nJXkiWRHF/jxs9/qI8AtTzlTHUnXAQ4XriLYKBbPbQdATzXhn3tZbVvCZTZmsm1uJ0A/9i4dWtelgkgowzeuVVCQJBAPdXKnccO+AWBc3h4YFk1WS3sxx65AFqE9517iqpIoRB2gEnwxsReAdDGCXOye0C7+q5eutopoTGTJOQiEgqhVUCQQCaLXn43b/YoXJjbrNr2SjnzRaTy1nWHiTW0jCvfBJM+EqEpPfrRXmvGIAhIOsYTSUKY4edfxEnEkTeDU1+aPnnAkEA8H6NqNEIGwPu0tf9911+6/Z+LoQDLKji9tx+HnbkO+r3uUXbPHeI2K7RTPm7dzvy4a1Fqp3Pw6w4iwburBTEHQJAYzaSf+hKtR+nWX76LJOQ9CGQvsij5dp+AFNACxz/NdKtOVBjTV3m4RsWELt7LacvB9Fmip4jLo5eDLpovMjWzwJBANfFFdGxzZfH4D5dL9LDhSKslmIew7h2RHT16jUZPDbiOEIvMGXYE1BE5HuiliLt7fNFj3hcFqACTqTtbLoKHOw=
    18:30:52.336 [main] INFO cn.zlc.des.rsa.RSAUtil - decryptionString by privateKey ,decryptionString is: 待加密数据
    
    展开全文
  • 基于RSA的数字签名算法的实现,能够用在VC6.0 平台运行。RSA加密算法中,消息发送方是用公钥对数据进行加密,消息接收方用...在RSA签名算法中,消息发布者用私钥对消息进行签名,消息接收者用签名者的公钥进行验证。

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 75,205
精华内容 30,082
关键字:

rsa签名

友情链接: yasea-master.zip