使用crypto-js对文件进行AES加解密

AES encryption and decryption of files using crypto-js

我目前有这样的需求,但是加密后的文件无法解密,生成的文件总是损坏打不开,不知道问题出在哪里。下面贴出的代码是我在VUE中使用的代码。

Encode() {
           let CryptoJS = require("crypto-js");
            this.file_mime = this.file.type;
            this.file_name = this.file.name;
            let reader = new FileReader();
            reader.onload = () => {
                let key = "1234567887654321";
                // let wordArray = CryptoJS.lib.WordArray.create(reader.result);
                // let plaintext = CryptoJS.enc.Hex.stringify(wordArray);
                let encrypted = CryptoJS.AES.encrypt(reader.result, key).toString();

                this.file2 = new Blob([encrypted], {
                    type: this.file_mime
                });
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(this.file2);
                const filename = this.file_name;
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            };
            reader.readAsBinaryString(this.file);
        }

Decode() {
            let CryptoJS = require("crypto-js");
            let reader = new FileReader();
            reader.onload = () => {
                let key = "1234567887654321";
                let decrypted = CryptoJS.AES.decrypt(reader.result, key).toString(CryptoJS.enc.Utf8)
                this.file2 = new Blob([decrypted], {type: this.file_mime});
                const a = document.createElement("a");
                const url = window.URL.createObjectURL(this.file2);
                const filename = this.file_name;
                a.href = url;
                a.download = filename;
                a.click();
                window.URL.revokeObjectURL(url);
            };
            reader.readAsBinaryString(this.file);
        }

在 JavaScript 中有几种数组类型:Array, ArrayBuffer and typed arrays. CryptoJS also uses WordArray。您必须在这些类型之间正确转换。

用于加密,FileReader.readAsBinaryString should be replaced by FileReader.readAsArrayBuffer, which returns the binary data from the file as an ArrayBuffer. In the encryption-method the ArrayBuffer can be converted into a WordArray which can be processed directly by CryptoJS.AES.encrypt. CryptoJS.AES.encrypt returns the ciphertext as CipherParams object (here),用toString()转换为OpenSSL格式的Base64编码字符串。该字符串可用于直接创建 blob。

注意:由于密钥在 CryptoJS.AES.encrypt 中作为字符串传递,因此它被解释为密码短语,并使用 OpenSSL 使用的相同算法生成随机的 8 字节盐,从中连同生成密码、密钥和 IV。密文前面是一个 16 字节的块,由 Salted__ 的 ASCII 编码组成,后面是 8 字节的盐,整个内容是 Base64 编码的。因此,在这种 OpenSSL 格式中,Base64 编码数据以 U2FsdGVkX1here and here 开头。

加密方法的变化:

function encrypt(input) {
    var file = input.files[0];
    var reader = new FileReader();
    reader.onload = () => {
        var key = "1234567887654321";
        var wordArray = CryptoJS.lib.WordArray.create(reader.result);           // Convert: ArrayBuffer -> WordArray
        var encrypted = CryptoJS.AES.encrypt(wordArray, key).toString();        // Encryption: I: WordArray -> O: -> Base64 encoded string (OpenSSL-format)

        var fileEnc = new Blob([encrypted]);                                    // Create blob from string

        var a = document.createElement("a");
        var url = window.URL.createObjectURL(fileEnc);
        var filename = file.name + ".enc";
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    };
    reader.readAsArrayBuffer(file);
}

注意:由于加密后的数据是Base64编码的,而Base64编码有一个overhead of 33%,所以加密后的数据相对于未加密的数据相应的更大

为了解密,FileReader.readAsBinaryString应该替换为FileReader.readAsText, because the encrypted data are stored as a Base64 encoded string (in OpenSSL format), which can be passed directly to CryptoJS.AES.decrypt. This string is implicitly converted into a CipherParams object (here,或者,可以显式传递一个CipherParams对象)。 CryptoJS.AES.decrypt returns 解密数据为 WordArray,因此必须转换为类型化数组或 ArrayBuffer 才能创建 blob。为此,可以使用以下函数:

function convertWordArrayToUint8Array(wordArray) {
    var arrayOfWords = wordArray.hasOwnProperty("words") ? wordArray.words : [];
    var length = wordArray.hasOwnProperty("sigBytes") ? wordArray.sigBytes : arrayOfWords.length * 4;
    var uInt8Array = new Uint8Array(length), index=0, word, i;
    for (i=0; i<length; i++) {
        word = arrayOfWords[i];
        uInt8Array[index++] = word >> 24;
        uInt8Array[index++] = (word >> 16) & 0xff;
        uInt8Array[index++] = (word >> 8) & 0xff;
        uInt8Array[index++] = word & 0xff;
    }
    return uInt8Array;
}

注意:将 WordArray 转换为 Utf8 字符串(如发布的代码中所示)是不可能的,并且通常会损坏数据,因为二进制数据(例如来自 pdf 的数据)包含任意字节序列通常不对应于 Utf8 编码(因为二进制数据不包含可打印字符),here

解密方法的变化:

function decrypt(input) {
    var file = input.files[0];
    var reader = new FileReader();
    reader.onload = () => {
        var key = "1234567887654321";  

        var decrypted = CryptoJS.AES.decrypt(reader.result, key);               // Decryption: I: Base64 encoded string (OpenSSL-format) -> O: WordArray
        var typedArray = convertWordArrayToUint8Array(decrypted);               // Convert: WordArray -> typed array

        var fileDec = new Blob([typedArray]);                                   // Create blob from typed array

        var a = document.createElement("a");
        var url = window.URL.createObjectURL(fileDec);
        var filename = file.name.substr(0, file.name.length - 4) + ".dec";
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    };
    reader.readAsText(file);
}