entronad / crypto-es

A cryptography algorithms library
Other
275 stars 31 forks source link

Problem in encrypting/decrypting multiple values at the same time #47

Open alizarei95 opened 5 months ago

alizarei95 commented 5 months ago

Hi, When using library in single thread, everything works well but when I'm using it in multi thread condition, results are not expected. In both encryption and decryption I'm getting wrong results. Is there any workaround?

import {AES} from "../libs/crypto-es/aes.js";
import {Hex, WordArray} from "../libs/crypto-es/core.js";
import * as CryptoESCore from "../libs/crypto-es/cipher-core.js";
import {NoPadding} from "../libs/crypto-es/pad-nopadding.js";
import {ZeroPadding} from "../libs/crypto-es/pad-zeropadding.js";

/**
 * Encrypt data using AES/CBC/ZEROPADDING
 * @param key {ArrayBuffer} Bytes of encryption key
 * @param iv {ArrayBuffer} Bytes of iv
 * @param content {ArrayBuffer} Bytes of plain content
 * @returns {string} Encrypted content in hex format
 */
export function encryptAES_CBC_ZEROPADDING(key, iv, content) {
    return AES.encrypt(WordArray.create(content), WordArray.create(key), {
        iv: WordArray.create(iv),
        mode: CryptoESCore.CBC,
        padding: ZeroPadding
    }).ciphertext.toString()
}

/**
 * Decrypt data using AES/CBC/ZEROPADDING
 * @param key {ArrayBuffer} Bytes of decryption key
 * @param iv {ArrayBuffer} Bytes of iv
 * @param cipherHex {string} Cipher text in HEX format
 * @return {string} Decrypted content in hex format
 */
export function decryptAES_CBC_ZEROPADDING(key, iv, cipherHex) {
    let cipherParams = CryptoESCore.CipherParams.create({
        ciphertext: Hex.parse(cipherHex)
    })
    return AES.decrypt(cipherParams, WordArray.create(key), {
        iv: WordArray.create(iv),
        mode: CryptoESCore.CBC,
        padding: ZeroPadding
    }).toString()
}