# js-aes-encryption-example **Repository Path**: fuile/js-aes-encryption-example ## Basic Information - **Project Name**: js-aes-encryption-example - **Description**: AES Encryption and JAVA Decryption example for javascript - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-12-11 - **Last Updated**: 2021-12-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AES Encryption ![PIC](document/pic.png) ## Project (Install) ``` npm install npm run serve ``` Demo (VueJS): - [http://localhost:8080](http://localhost:8080) Requirements: - [Crypto-js Library](https://www.npmjs.com/package/crypto-js/v/3.1.9-1) ^3.1.9-1 ```javascript // "crypto-js": "^3.1.9-1" import CryptoJS from 'crypto-js' ``` Usage: ```javascript // 使用用户名合成盐值 const salt = CryptoJS.MD5(this.user.username).toString() // 基数 const base = (v) => (v.length - 16) / 2 // 从盐中取出密钥 const key = salt.slice(base(salt), base(salt) + 16) // 从盐中取出向量 let iv = salt.slice(0, base(salt)) + salt.slice(base(salt) + 16) // 向量偏移量 iv = iv.slice(base(iv), base(iv) + 16) // Base64化后的加密密文 let ciphertext = this.encrypt(this.user.password, key, iv) ``` AES Encryption (Javascript): ```javascript /** * 原文加密 * @param src 原文值 * @param key 密钥值 * @param iv 向量值 */ encrypt(src, key, iv) { const encrypted = CryptoJS.AES.encrypt( CryptoJS.enc.Utf8.parse(src), CryptoJS.enc.Utf8.parse(key), { iv: CryptoJS.enc.Utf8.parse(iv), mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, } ) return CryptoJS.enc.Base64.stringify(encrypted.ciphertext) } ``` AES Decryption (Java): ```java // Use case public void login(UserLoginForm form) { form.setAccount("test"); form.setPassword("WTjNxSNUfLrIi2y/lUwSXg=="); String rawPassword = signatureValid(form); Assert.notNull(rawPassword, "用户名或密码错误"); } @Data public class UserLoginForm { private String account; private String password; } private String signatureValid(UserLoginForm form) { try { String salt = DigestUtils.md5DigestAsHex(form.getAccount().getBytes(StandardCharsets.UTF_8)); String key = salt.substring(base(salt), base(salt) + 16); String iv = salt.substring(0, base(salt)) + salt.substring(base(salt) + 16); iv = iv.substring(base(iv), base(iv) + 16); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8)); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encrypted = Base64Utils.decodeFromString(form.getPassword()); byte[] original = cipher.doFinal(encrypted); return new String(original, StandardCharsets.UTF_8); } catch (Exception e) { e.printStackTrace(); } return null; } private int base(String v) { return (v.length() - 16) / 2; } ```