Vue中使用RAS加密

1、安装依赖

npm install jsencrypt

2、main.js 引入依赖

import JsEncrypt from 'jsencrypt'
//密码加密 RSA加密
Vue.prototype.$jsEncrypt = function(psd){
  let encry = new JsEncrypt();
  encry.setPublicKey('秘钥');
  let data = encry.encrypt(psd);
  return data;
}

3、代码中使用

let params={};
params.accountName=this.$jsEncrypt(this.username);
params.password=this.$jsEncrypt(this.password);

tip

前端用公钥加密,后端用私钥解密

后端RAS解密

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

import javax.crypto.Cipher;
import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAUtil{

    public static final String KEY_ALGORITHM = "RSA";

   private static final String defaultPrivateKey = "私钥";

    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }
    public static String decryptByPrivateKey(String data)throws Exception {
        byte[] decodedData= decryptByPrivateKey(decryptBASE64(data),defaultPrivateKey);
        String decodedStr = new String(decodedData);
        return decodedStr;
    }

    public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
}

后端使用

try {
    loginname= RSAUtil.decryptByPrivateKey(loginname);
} catch (Exception e) {
    result.setMessage("账号解密错误!");
    return result;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值