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

相关推荐
胡西风_foxww13 分钟前
【ES6复习笔记】数值扩展(16)
前端·笔记·es6·扩展·数值
mosen86815 分钟前
uniapp中uni.scss如何引入页面内或生效
前端·uni-app·scss
白云~️15 分钟前
uniappX 移动端单行/多行文字隐藏显示省略号
开发语言·前端·javascript
沙尘暴炒饭17 分钟前
uniapp 前端解决精度丢失的问题 (后端返回分布式id)
前端·uni-app
昙鱼31 分钟前
springboot创建web项目
java·前端·spring boot·后端·spring·maven
天天进步201537 分钟前
Vue项目重构实践:如何构建可维护的企业级应用
前端·vue.js·重构
小华同学ai40 分钟前
vue-office:Star 4.2k,款支持多种Office文件预览的Vue组件库,一站式Office文件预览方案,真心不错
前端·javascript·vue.js·开源·github·office
APP 肖提莫41 分钟前
MyBatis-Plus分页拦截器,源码的重构(重构total总数的计算逻辑)
java·前端·算法
问道飞鱼1 小时前
【前端知识】强大的js动画组件anime.js
开发语言·前端·javascript·anime.js
k09331 小时前
vue中proxy代理配置(测试一)
前端·javascript·vue.js