在Python和JavaScript中进行数据加密和解密,通常需要使用一些加密库。这里我将分别为你提供Python和JavaScript的示例代码,以展示如何使用AES加密和解密数据。
Python 示例:
首先,你需要安装pycryptodome
库,可以使用以下命令安装:
pip install pycryptodome
然后,你可以使用以下代码进行AES加密和解密:
from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Util.Padding import pad, unpad import base64 def encrypt(data, key): cipher = AES.new(key, AES.MODE_CBC) ct_bytes = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size)) iv = base64.b64encode(cipher.iv).decode('utf-8') ct = base64.b64encode(ct_bytes).decode('utf-8') return iv + ':' + ct def decrypt(encrypted_data, key): iv, ct = encrypted_data.split(':') iv = base64.b64decode(iv) ct = base64.b64decode(ct) cipher = AES.new(key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(ct), AES.block_size).decode('utf-8') key = get_random_bytes(16) data = 'https://www.yisu.com/ask/Hello, World!' encrypted_data = https://www.yisu.com/ask/encrypt(data, key)'Encrypted data:', encrypted_data) decrypted_data = https://www.yisu.com/ask/decrypt(encrypted_data, key)'Decrypted data:', decrypted_data)
JavaScript 示例:
在JavaScript中,你可以使用crypto-js
库进行AES加密和解密。首先,你需要安装这个库:
npm install crypto-js
然后,你可以使用以下代码进行AES加密和解密:
const CryptoJS = require('crypto-js'); function encrypt(data, key) { const iv = CryptoJS.lib.WordArray.random(16); const encrypted = CryptoJS.AES.encrypt(data, key, { iv: iv }); return iv.concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64); } function decrypt(encryptedData, key) { const [iv, ciphertext] = encryptedData.split(':'); const decodedIV = CryptoJS.enc.Base64.parse(iv); const decodedCiphertext = CryptoJS.enc.Base64.parse(ciphertext); const decrypted = CryptoJS.AES.decrypt({ ciphertext: decodedCiphertext }, key, { iv: decodedIV }); return decrypted.toString(CryptoJS.enc.Utf8); } const key = CryptoJS.lib.WordArray.random(16).toString(); const data = 'https://www.yisu.com/ask/Hello, World!'; const encryptedData = https://www.yisu.com/ask/encrypt(data, key);'Encrypted data:', encryptedData); const decryptedData = https://www.yisu.com/ask/decrypt(encryptedData, key);'Decrypted data:', decryptedData);
这些示例代码展示了如何在Python和JavaScript中使用AES加密和解密数据。请注意,为了确保数据安全,你需要妥善保管加密密钥。