java和vue使用AES加密验证前端请求

前段时间python团队做的项目因为存在短信被盗刷的漏洞,公司的几万条短信几日之内全被消耗干净了。由于短信接口是对外的,无法被oauth2等鉴权,鉴于此,我们java团队使用了AES加密一个字段来校验请求是否是用户在我们平台发出的请求。其次,也对用户ip做了缓存,控制其访问次数,这里只说java的AES加密:

主要流程是前端调用AES的加密方法,这里前端使用的是VUE。
import CryptoJS from 'crypto-js/crypto-js'

export function Encrypt(word, keyStr, ivStr) {
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  let srcs = CryptoJS.enc.Utf8.parse(word);
  var encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

}

获取到加密后的字符串,调用后端接口API时,做为一个参数发送到后端;

后端取到数据后,按照约定好的salt去 ①再次加密比较,②解密后比较。即可校验出来;

public static String encrypt(String data, String key, String iv) throws Exception {
    try {

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/补码方式"NoPadding PkcsPadding
        int blockSize = cipher.getBlockSize();

        byte[] dataBytes = data.getBytes();
        int plaintextLength = dataBytes.length;
        if (plaintextLength % blockSize != 0) {
            plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
        }

        byte[] plaintext = new byte[plaintextLength];
        System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(plaintext);

        return new Base64().encodeToString(encrypted);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

附上vue解密和java解密的代码:

vue
export function Decrypt(word, keyStr, ivStr) {
  let key  = KEY
  let iv = IV

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

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

  var decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.ZeroPadding
  });

  var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
java
public static String desEncrypt(String data, String key, String iv) throws Exception {
    try {
        byte[] encrypted1 = new Base64().decode(data);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
        IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

你可能感兴趣的:(java,vue,记录)