如何在 vue 用 RSA加密,java 后端 RSA解密

第一步:安装crypto-js 库

npm install crypto-js --save-dev

第二步:在Vue项目中导入全局变量

import crypto from "crypto";
Vue.prototype.$crypto = crypto;

第三步:前端页面加密

submitLogin() {
	// key值
	let key = CryptoJS.enc.Utf8.parse("852asd1a6s9s8z3w");
	console.log(key);
	// 密码
	let password = CryptoJS.enc.Utf8.parse(password);
	// 进行加密
	let encrypted = CryptoJS.AES.encrypt(password, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
	let encryptedPwd = encrypted.toString();
	console.log("encrypted = " + encrypted);
	console.log("encryptedPwd = " + encryptedPwd);
	
	// 传输给后端接口
	this.$refs.usernameLoginForm.validate(valid => {
	if (valid) {
		login({
			username: this.form.username,
			password: encryptedPwd,
			key: this.key
		}).then(res => {
			if('success' === res.msg) {
				this.$Message.success("登录成功")
			}
		});
	}
	});
		
}

第四步:后台加密代码工具类

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 加密工具类
 *
 * @date 2019/7/18 11:43
 */
public class AesUtils {
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param content
     * @param key
     * @return
     */
    public static String encrypt(String content, String key) {
        try {
            //获得密码的字节数组
            byte[] raw = key.getBytes();
            //根据密码生成AES密钥
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            //根据指定算法ALGORITHM自成密码器
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            //初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            //获取加密内容的字节数组(设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
            byte[] byte_content = content.getBytes("utf-8");
            //密码器加密数据
            byte[] encode_content = cipher.doFinal(byte_content);
            //将加密后的数据转换为字符串返回
            return Base64.encodeBase64String(encode_content);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密
     *
     * @param encryptStr
     * @param decryptKey
     * @return
     */
    public static String decrypt(String encryptStr, String decryptKey) {
        try {
            //获得密码的字节数组
            byte[] raw = decryptKey.getBytes();
            //根据密码生成AES密钥
            SecretKeySpec skey = new SecretKeySpec(raw, "AES");
            //根据指定算法ALGORITHM自成密码器
            Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
            //初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
            cipher.init(Cipher.DECRYPT_MODE, skey);
            //把密文字符串转回密文字节数组
            byte[] encode_content = Base64.decodeBase64(encryptStr);
            //密码器解密数据
            byte[] byte_content = cipher.doFinal(encode_content);
            //将解密后的数据转换为字符串返回
            return new String(byte_content, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

第五步:Controller接口

@RestController
@RequestMapping(value = {"/hello"})
public class HelloController{

    @PostMapping("/get/key")
    @ApiOperation("得到解密验证码key")
    public R getUUIDKey() {
        String key = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        return R.ok().put("key", key);
    }

    @PostMapping(value = {"/login"})
    @ApiOperation(value = "登入")
    public XResult login(@RequestBody @ApiParam(value = "登入数据", required = true)     SysLoginForm form) {
	RestUserEntity userEntity = userService.findByUserName(form.getUsername());
	String decryptPassword = AesUtils.decrypt(form.getPassword(), form.getKey());
	if (!userEntity.getPassword().equals(decryptPassword)) {
		return R.error("账号或密码错误");
	}
	
	return XResult.ok("登录成功");
}

}

第六步:实体类SysLoginForm

import lombok.Data;

@Data
public class implements Serializable {
    private static final long serialVersionUID = 1L;

    private String username;
    private String password;
    private String key;
}

注:这里推荐使用lombok 插件,它可以帮你把getter/setter,hashCode/toString,全参构造器/无参构造器全部自动生成,并且自动帮你打理

第七步:结果展示

如何在 vue 用 RSA加密,java 后端 RSA解密_第1张图片

 

你可能感兴趣的:(java,web,Vue)