python aes cbc:
from Crypto.Cipher import AES
import base64
# 将字符串补全为16的倍数
def pad(text):
return text + b"\0" * (AES.block_size - len(text) % AES.block_size)
# 加密函数
def encrypt(key, plaintext):
plaintext = pad(plaintext)
iv = bytes.fromhex('00000000000000000000000000000000')
cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(plaintext)
return base64.b64encode(ciphertext).decode('utf-8')
# 解密函数
def decrypt(key, ciphertext):
ciphertext = base64.b64decode(ciphertext)
iv = bytes.fromhex('00000000000000000000000000000000')
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext)
return plaintext.rstrip(b"\0").decode('utf-8')
# 测试
key = b'0123456789abcdef'
plaintext = b'This is a secret message!'
ciphertext = encrypt(key, plaintext)
print(ciphertext)
decrypted = decrypt(key, ciphertext)
print(decrypted)
javascript aes cbc:
async function encryptCBC(key, iv, data) {
const blockSize = 16;
const dataBuffer = new TextEncoder().encode(data);
// Pad the data with PKCS#7 padding
const paddingLength = blockSize - (dataBuffer.byteLength % blockSize);
const paddedDataBuffer = new Uint8Array(dataBuffer.byteLength + paddingLength);
paddedDataBuffer.set(dataBuffer);
paddedDataBuffer.fill(paddingLength, dataBuffer.byteLength);
const cipher = await window.crypto.subtle.importKey(
"raw",
key,
"AES-CBC",
false,
["encrypt"]
);
const encryptedBlocks = [];
let previousCipherBlock = iv;
for (let i = 0; i < paddedDataBuffer.byteLength; i += blockSize) {
const block = paddedDataBuffer.subarray(i, i + blockSize);
const xorBlock = new Uint8Array(block.length);
for (let j = 0; j < block.length; j++) {
xorBlock[j] = block[j] ^ previousCipherBlock[j];
}
const cipherBlock = await window.crypto.subtle.encrypt(
{
name: "AES-CBC",
iv: iv,
},
cipher,
xorBlock
);
encryptedBlocks.push(new Uint8Array(cipherBlock));
previousCipherBlock = new Uint8Array(cipherBlock);
}
// Combine all the encrypted blocks into one Uint8Array
const encryptedDataBuffer = new Uint8Array(
encryptedBlocks.reduce(
(accumulator, currentValue) => accumulator + currentValue.byteLength,
0
)
);
let offset = 0;
encryptedBlocks.forEach((block) => {
encryptedDataBuffer.set(block, offset);
offset += block.byteLength;
});
// Convert the Uint8Array to a hex string
const encryptedDataHex = Array.prototype.map
.call(encryptedDataBuffer, (x) => ("00" + x.toString(16)).slice(-2))
.join("");
return encryptedDataHex;
}
// Generate a random 128-bit key
const keyy = new TextEncoder().encode('qwertyuiopasdfgh');
// Generate a random 128-bit initialization vector (IV)
const ivv = new TextEncoder().encode('0000000000000000');
// Encrypt the data using AES-CBC mode
const data = "message"
const encryptedDataHex = await encryptCBC(keyy, ivv, data);
console.log(encryptedDataHex);