转自CHATGPT,请自行斟酌!
在微信小程序中使用 AES 加解密,涉及到前端小程序代码和后端 Java 代码的协同工作。我们将分别讨论如何在微信小程序中进行 AES 加密以及在 Java 后端进行解密。
微信小程序端
在微信小程序中,可以使用 crypto-js
库来实现 AES 加密。首先,需要安装 crypto-js
库:
-
在项目根目录下安装
crypto-js
:npm install crypto-js
-
在微信小程序代码中使用
crypto-js
进行加密:// 引入crypto-js const CryptoJS = require('crypto-js'); // AES加密 function encrypt(message, key) { const keyUtf8 = CryptoJS.enc.Utf8.parse(key); const ivUtf8 = CryptoJS.enc.Utf8.parse(key); // 这里iv可以和key相同,也可以设定其他值 const encrypted = CryptoJS.AES.encrypt(message, keyUtf8, { iv: ivUtf8, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return encrypted.toString(); } // AES解密 function decrypt(encryptedMessage, key) { const keyUtf8 = CryptoJS.enc.Utf8.parse(key); const ivUtf8 = CryptoJS.enc.Utf8.parse(key); // 这里iv可以和key相同,也可以设定其他值 const decrypted = CryptoJS.AES.decrypt(encryptedMessage, keyUtf8, { iv: ivUtf8, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); return decrypted.toString(CryptoJS.enc.Utf8); } // 示例 const message = "Hello, World!"; const key = "1234567890123456"; // AES密钥,需与后端保持一致 const encryptedMessage = encrypt(message, key); console.log("Encrypted Message: ", encryptedMessage); const decryptedMessage = decrypt(encryptedMessage, key); console.log("Decrypted Message: ", decryptedMessage);
Java 后端
在 Java 后端,我们可以使用 javax.crypto
包来实现 AES 解密。以下是一个示例:
-
添加依赖(如果使用 Maven):
<dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency>
-
实现 AES 解密:
import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AESUtil { // 解密 public static String decrypt(String encryptedMessage, String key) throws Exception { byte[] raw = key.getBytes("UTF-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); IvParameterSpec iv = new IvParameterSpec(raw); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedMessage)); return new String(original); } public static void main(String[] args) { try { String key = "1234567890123456"; // AES密钥,需与前端保持一致 String encryptedMessage = "前端加密后的消息"; String decryptedMessage = decrypt(encryptedMessage, key); System.out.println("Decrypted Message: " + decryptedMessage); } catch (Exception ex) { ex.printStackTrace(); } } }
关键点
- 密钥和 IV:AES 加密和解密需要使用相同的密钥(
key
)和初始化向量(iv
)。为了简化示例,iv
在此与key
相同,但在实际应用中,iv
应该是独立且随机的。 - 编码格式:确保前后端使用相同的编码格式(如
UTF-8
)。 - 填充模式:前后端应使用相同的填充模式(此示例中为
PKCS7
和PKCS5
,它们在实际使用中是兼容的)。
通过上述方法,你可以在微信小程序中实现 AES 加密,并在 Java 后端进行解密。确保密钥和其他参数在前后端保持一致,以确保加解密过程的正确性。