RSA非对称加密-前端加密,java 后端解密

思路:

  1. 后端生成私钥、公钥。
  2. 前端用公钥对信息加密,后端用私钥解密。

后端代码:

java 复制代码
package com.example.demo.utils;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import lombok.AllArgsConstructor;
import lombok.Data;

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;

public class RSAUtil {

    public static String RSA_ALGORITHM = "RSA";
    public static String UTF8 = "UTF-8";

    /**
     * 密钥长度,DSA算法的默认密钥长度是1024
     * 密钥长度必须是64的倍数,在512到65536位之间
     * */
    private static final int KEY_SIZE=1024;

    public static void test() throws Exception {
        String password = "jiang=xxu&xxuxu-aa=xxxx@cummins.com%";


        RSAKey key = createKey();


        byte[] encryptByPublicKey = encryptByPublicKey(password.getBytes(), Base64.decode(key.getPublicKey()));
        System.out.println("使用公钥加密后的数据:"+Base64.encode(encryptByPublicKey));


        byte[] decryptByPrivateKey = decryptByPrivateKey(encryptByPublicKey, Base64.decode(key.getPrivateKey()));
        System.out.println("使用私钥解密后的数据:"+new String(decryptByPrivateKey));

    }

    public static void main(String[] args) throws Exception {
        
        String pwd_encode =
                "TI6CDLwMb3Wbmgt4MPiGGTIqIBeFoyp8SF6lbsoCI8j5ee9qFB7q0OLpgQGwYD1DddU1+mLmnq62cp4dfm42EpSDU8+P3prxiKJeuwAKcOnIq2Uf1MpCF+eEyzLYxiAHjTDcW7o0070bASxz92O0uL0D87wKAx5sO4ch2Rr1kcI="                ;

        /**
         * 放在前端加密
         */
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeFyVkUDrMAbn0WhDzI1IA+/z0m1k286A3AgzckLT0JKRFXvykkfQEYcymS4ncuCq/Im+CHVCs5L1ZU/hPoXvNhfwMEiXWx4PG1JUOrufl5cueizrsxIMJvQQki058wDyxEm0p6d8v9lFw5IAlTA5pQS6mZEhdPPdxVGABS1e0JQIDAQAB";

        /**
         * 放在后端解密
         */
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ4XJWRQOswBufRaEPMjUgD7/PSbWTbzoDcCDNyQtPQkpEVe/KSR9ARhzKZLidy4Kr8ib4IdUKzkvVlT+E+he82F/AwSJdbHg8bUlQ6u" +
                "5+Xly56LOuzEgwm9BCSLTnzAPLESbSnp3y/2UXDkgCVMDmlBLqZkSF0893FUYAFLV7QlAgMBAAEC" +
                "gYBLxAoOnojfVwB5BGVVMZtOj3Y3APDr7izd0CS73Lpsu9bizFhGwxBwvTJojJFg7/7EpctNT6Fn" +
                "iyTYV+8Msvby0sDmm40CJOQJazMyqUjAWnzsVsdBKRjZlAmc37T38U0Rmq1dARmhKAPQAvp8PEhh" +
                "gx4xh/DrSYuUmwZk/4hYAQJBANbh0PkcGzjKgkSPBsAdimq/C386ILakixbf/zyX4WqokEcTYpbd" +
                "IaTWYZ9PMoJ2gN0Ad0YXkfZTItrtlCGQBgECQQC8V1cwYl9FFyB2Q0qf6AD3khbzCH/1PPZGdeeI" +
                "MS954575ij6HtlwgSuGzzl/HO5zjjy2gEuNMx75qwGcAgtYlAkEAtS0WvkMFbL/KUDXrsiX2JATK" +
                "k84V8QkRQQtCL/u7EuvnIhZlJOBz0oDzNJhY9Qkno68V4eJTrkXweHiiUh4WAQJAfEfuIuFnGIJQ" +
                "S3nQDoDb0oI2Xp0nQr69jHVVGUvLllUbnHMbHBa76BtBoJL4JNIzjv32D4EnOI0+G9dmoLG1eQJB" +
                "AMcM+8LIuJjp8WzHZ7OqaWlmHaEBwax+luvYPSd4ozBUyQlEmipQHdCBxXU+kBtQaDDaGKYxOGW5" +
                "Y0nK8/bT+jg=";

        byte[] old = decryptByPrivateKey(Base64.decode(pwd_encode),Base64.decode(privateKey));
        System.out.println(new String(old));
    }

    public static RSAKey  createKey() throws NoSuchAlgorithmException {

        KeyStore keys = createKeyStore();
        byte[] publicKey = getPublicKey(keys);
        byte[] privateKey = getPrivateKey(keys);

        String encode_publicKey = Base64.encode(publicKey);
        System.out.println("公钥:"+encode_publicKey );
        System.out.println();

        String endcode_privateKey = Base64.encode(privateKey);
        System.out.println("私钥:"+ endcode_privateKey);

        return new RSAKey(endcode_privateKey,encode_publicKey);
    }

    @Data
    public static class RSAKey{

        private String privateKey;
        private String publicKey;

        public RSAKey(String privateKey, String publicKey) {
            this.privateKey = privateKey;
            this.publicKey = publicKey;
        }
    }


    /**
     * 生成密钥对
     * @return 密钥对对象
     * @throws NoSuchAlgorithmException
     */
    private static KeyStore createKeyStore() throws NoSuchAlgorithmException {
        //KeyPairGenerator用于生成公钥和私钥对。密钥对生成器是使用 getInstance 工厂方法
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        KeyStore keyStore = new KeyStore( publicKey, privateKey);
        return keyStore;
    }

    /**
     * 获取私钥
     * @param keyStore
     * @return
     */
    private static byte[] getPrivateKey(KeyStore keyStore){
        return ((RSAPrivateKey)keyStore.privateKey).getEncoded();
    }

    /**
     * 获取公钥
     * @param keyStore
     * @return
     */
    private static byte[] getPublicKey(KeyStore keyStore){
        return ((RSAPublicKey)keyStore.publicKey).getEncoded();
    }

    /**
     * 私钥加密
     * @param data 待加密数据
     * @param key 密钥
     * @return byte[] 加密数据
     * */
    public static byte[] encryptByPrivateKey(byte[] data,byte[] key) throws Exception{

        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory= KeyFactory.getInstance(RSA_ALGORITHM);
        //生成私钥
        PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec);
        //数据加密
        Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 公钥加密
     * @param data
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws NoSuchPaddingException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws InvalidKeyException
     */
    private static byte[] encryptByPublicKey(byte[] data, byte[] key) throws NoSuchAlgorithmException,
            InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
        //实例化密钥工厂
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        //初始化公钥,根据给定的编码密钥创建一个新的 X509EncodedKeySpec。
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        //数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        return cipher.doFinal(data);
    }

    /**
     * 私钥解密
     * @param data 待解密数据
     * @param key 密钥
     * @return byte[] 解密数据
     * */
    public static byte[] decryptByPrivateKey(byte[] data,byte[] key) throws Exception{
        //取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM);
        //生成私钥
        PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec);
        //数据解密
        Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }



    /**
     * 公钥解密
     * @param data 待解密数据
     * @param key 密钥
     * @return byte[] 解密数据
     * */
    public static byte[] decryptByPublicKey(byte[] data,byte[] key) throws Exception{

        //实例化密钥工厂
        KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM);
        //初始化公钥
        //密钥材料转换
        X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(key);
        //产生公钥
        PublicKey pubKey=keyFactory.generatePublic(x509KeySpec);
        //数据解密
        Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, pubKey);
        return cipher.doFinal(data);
    }


    //定义密钥类
    @Data
    @AllArgsConstructor
    public static class KeyStore{
        private Object publicKey;
        private Object privateKey;
    }
}

注意事项:后端生成 私钥(base64加密的私钥)和公钥(base64加密的公钥),记得保存。

然后将上面公钥复制到前端,前端对信息加密即可。

html 复制代码
<!DOCTYPE html>
<html>

<head>
    <!-- <script src="./encode/base64.js"></script> -->
    <script src="./encode/jsencrypt.js"></script>
</head>

<body>
    hello ,world!
    <div id="pwd_encode"></div>
</body>
<script>


    // 非对称加密(RSA)

    // 密钥对生成 http://web.chacuo.net/netrsakeypair

    /**
     * 前端加密时需要公钥
     */ 
    const publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeFyVkUDrMAbn0WhDzI1IA+/z0m1k286A3AgzckLT0JKRFXvykkfQEYcymS4ncuCq/Im+CHVCs5L1ZU/hPoXvNhfwMEiXWx4PG1JUOrufl5cueizrsxIMJvQQki058wDyxEm0p6d8v9lFw5IAlTA5pQS6mZEhdPPdxVGABS1e0JQIDAQAB";


    /**
     * 没啥用
     */
    const privateKey = ''

    // 加密
    function encrypt(txt) {

        const encryptor = new JSEncrypt()

        encryptor.setPublicKey(publicKey) // 设置公钥

        return encryptor.encrypt(txt) // 对数据进行加密

    }

    // 解密
    function decrypt(txt) {

        const encryptor = new JSEncrypt()

        encryptor.setPrivateKey(privateKey) // 设置私钥

        return encryptor.decrypt(txt) // 对数据进行解密

    }



    //4.将需要的数据进行加密即可

    let pwd = "jiang=xxu&xxuxu-aa=xxxx@cummins.com%";

    let pwd_encode = encrypt(pwd)
    document.getElementById("pwd_encode").innerHTML=pwd_encode;

</script>

</html>

jsencrypt 库 可以去官网下载:下载

或者直接下载:https://download.csdn.net/download/rainyspring4540/89100890

相关推荐
M_emory_11 分钟前
解决 git clone 出现:Failed to connect to 127.0.0.1 port 1080: Connection refused 错误
前端·vue.js·git
Ciito14 分钟前
vue项目使用eslint+prettier管理项目格式化
前端·javascript·vue.js
成都被卷死的程序员1 小时前
响应式网页设计--html
前端·html
mon_star°1 小时前
将答题成绩排行榜数据通过前端生成excel的方式实现导出下载功能
前端·excel
Zrf21913184551 小时前
前端笔试中oj算法题的解法模版
前端·readline·oj算法
文军的烹饪实验室2 小时前
ValueError: Circular reference detected
开发语言·前端·javascript
Martin -Tang3 小时前
vite和webpack的区别
前端·webpack·node.js·vite
迷途小码农零零发3 小时前
解锁微前端的优秀库
前端
王解4 小时前
webpack loader全解析,从入门到精通(10)
前端·webpack·node.js
我不当帕鲁谁当帕鲁4 小时前
arcgis for js实现FeatureLayer图层弹窗展示所有field字段
前端·javascript·arcgis