VUE + JAVA (SpringBoot, strtus2) AES symmetric encryption

npm install crypto-js,base64-js


1. Front-end uniapp-vue

                Create a cryptoJS file. The key and iv must be consistent with those filled in the backend. 

import CryptoJS from 'crypto-js/crypto-js'

/*
 * 默认的 KEY IV     如果在加密解密的时候没有传入KEY和IV,就会使用这里定义的
 * 
 * 前后端交互时需要前后端**和初始向量保持一致
 */

const KEY = CryptoJS.enc.Utf8.parse("qP2$bG9;vA0^uW0:");//  **        长度必须为16位
const IV = CryptoJS.enc.Utf8.parse("qP2$bG9;vA0^uW0:");           //  初始向量    长度随意

/*
 * AES加密 :字符串 key iv  返回base64
 */
export function encrypt(str, keyStr, ivStr) {
    let key = KEY
    let iv = IV

    if (keyStr && ivStr) {
        key = CryptoJS.enc.Utf8.parse(keyStr);
        iv = CryptoJS.enc.Utf8.parse(ivStr);
    }

    let srcs = CryptoJS.enc.Utf8.parse(str);
    var encrypt = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,            //这里可以选择AES加密的模式
        padding: CryptoJS.pad.Pkcs7
    });
    return CryptoJS.enc.Base64.stringify(encrypt.ciphertext);
}

/*
 * AES 解密 :字符串 key iv  返回base64
 */
export function decrypt(str, keyStr, ivStr) {
    let key = KEY
    let iv = IV

    if (keyStr && ivStr) {
        key = CryptoJS.enc.Utf8.parse(keyStr);
        iv = CryptoJS.enc.Utf8.parse(ivStr);
    }

    let base64 = CryptoJS.enc.Base64.parse(str);
    let src = CryptoJS.enc.Base64.stringify(base64);

    var decrypt = CryptoJS.AES.decrypt(src, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,            //这里可以选择AES解密的模式
        padding: CryptoJS.pad.Pkcs7
    });

    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

 The way to use it is to import the newly created cryptoJS call and write the key agreed with the backend at the place of introduction

The following example is the key agreed between me and the background: eNWBld07ItKkWmw9#@^F

<template>	 
	<view>	 
	<web-view :src="url"></web-view>
		 <a href="/static/zppdf/web/viewer.html?file=http://192.168.1.8:8010/pdf/hz/2022/05/26/4028a8c480ff70da0180ff70da540000.pdf" >test</a> 
		   <a :href="url" >testeeee</a>
	</view>	 
</template>	 

<script>	 
import {
		getlist,
		downLoadPdf
	} from '@/pages/zpdemo/api/api.js'
	import {encrypt,decrypt} from '@/pages/utils/cryptoJS.js'
	export default {	 
		data() {	 
			return {	 
				url: '',
				requestId:{id:''}
			};	 
		},	 
		onLoad(option) {
			if (res=='none'){
				//没有PDF
			}else{
				this.requestId.id=option.id;
				this.url = '/static/zppdf/web/viewer.html?file=http://192.168.1.8:8010/mobile/cjHzpAction!PdfDownload.do'+encodeURIComponent(`?key=${encrypt('eNWBld07ItKkWmw9#@^F')}&id=${this.requestId.id}`);
			}
			
		},	 
	}	 
</script>	 

java codeAESUtils

package com.hxzk.util;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * AES加密,key的大小必须是16个字节
 * 如果没有指定分组密码模式和填充模式,ECB/PKCS5Padding就是默认值
 * 如果没有指定分组密码模式为CBC,必须指定初始向量,初始向量中密钥的长度必须是16个字节
 * NoPadding模式,原文的长度必须是16个字节的整倍数
 * @author juihai
 * @date 2021/4/13
 */
public class AESUtils {

    //获取Cipher对象的算法
    private static String transformation = "AES/CBC/PKCS5Padding";

    /**key **/
    public static final String  SJ_KEY="qP2$bG9;vA0^uW0:";

    public static final String  AES= "AES";

    /**
     * 加密
     * @param input  明文
     * @param key   密钥(AES,密钥的长度必须是16个字节)
     * @param algorithm   获取密钥的算法
     * @return  返回密文
     * @throws Exception
     */
    public static String encrypt(String input, String key, String algorithm) throws Exception {
        // 1,获取Cipher对象
        Cipher cipher = Cipher.getInstance(transformation);
        // 指定密钥规则
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        // 2.初始化向量的秘钥长度需要根据算法而定,des 8个字节长度  aes 16个字节长度
        IvParameterSpec iv = new IvParameterSpec(key.getBytes()); //java iv与key一样
        cipher.init(Cipher.ENCRYPT_MODE, sks, iv);
//        cipher.init(Cipher.ENCRYPT_MODE, sks);
        // 3. 加密
        byte[] bytes = cipher.doFinal(input.getBytes());
        // 对数据进行Base64编码
        String encode = Base64.encode(bytes);
        return encode;
    }

    /**
     * 解密
     * @param input  密文
     * @param key   密钥(AES,密钥的长度必须是16个字节)
     * @param algorithm   获取密钥的算法
     * @return 返回原文
     * @throws Exception
     */
    public static String decrypt(String input, String key, String algorithm) throws Exception {
        Cipher cipher = Cipher.getInstance(transformation);
        SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);
        IvParameterSpec iv = new IvParameterSpec(key.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, sks, iv);
//         cipher.init(Cipher.DECRYPT_MODE, sks);
        byte[] bytes = cipher.doFinal(Base64.decode(input));
        return new String(bytes);
    }
    
    
    
    public static void main(String[] args) {
		String jmqzf = "akjife;iiifej;'[asdfDFEFEFE<>>?<>??";
		String key = "5454545413185;'[";    //  约定的秘钥
		String sf = "AES";
		System.out.println("加密前字符串"+jmqzf);
		try {
			String jmhzf = encrypt(jmqzf,key,sf);
			System.out.println("加密后字符串"+jmhzf);
			String jiemhzf = decrypt(jmhzf,key,sf);
			System.out.println("解密后字符串"+jiemhzf);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    public static String dateFmtPassword(Date date){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMddHHHHHHHH");
        return simpleDateFormat.format(date);
    }
    

}

Then AESUTILS.decrypt(request.getparams('key')) Because the front end is encrypted and decrypted directly, it's over! Get the agreed key for subsequent judgment

Probably the calling method is inconsistent with the logic written before. Maybe it will be used in this way and there will be time to add normal logic.

Guess you like

Origin blog.csdn.net/liuchenhaoy/article/details/125020165