Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Encrypting Files NodeJS ERRO: EVP_DecryptFinal_ex:wrong final block length

My Code:

    const encrypt = (buffer, key) => {
        // Create an initialization vector
        const iv = crypto.randomBytes(16);
        // Create a new cipher using the algorithm, key, and iv
        const cipher = crypto.createCipheriv("aes-192-cbc", key, iv);
        // Create the new (encrypted) buffer
        const result = Buffer.concat([iv, cipher.update(buffer), cipher.final()]);
        return result;
    };

    function saveFile(pw, usersJson) {
        crypto.scrypt(pw, 'salt', 24, (err, key) => {
            if (err) {
                log.printlog("{'ERROR':'password-manager.saveFile.crypto.scrypt(PRIVATE)','message': " +
                    err.message + "}", 0);
            }
            var newStuff = JSON.stringify(usersJson);
            fs.writeFileSync(__dirname + "/userDB/" + user + ".json", encrypt(Buffer.from(newStuff), key), "utf8");
        });
    }

    const decrypt = (encrypted, key) => {
        // Get the iv: the first 16 bytes
        const iv = encrypted.slice(0, 16);
        // Get the rest
        encrypted = encrypted.slice(16);
        // Create a decipher
        const decipher = crypto.createDecipheriv("aes-192-cbc", key, iv);
        // Actually decrypt it
        const result = Buffer.concat([decipher.update(encrypted), decipher.final()]);
        return result;
    };


    function loadFile(pw) {
        crypto.scrypt(pw, 'salt', 24, (err, key) => {
            if (err) {
                log.printlog("{'ERROR':'password-manager.loadFile.crypto.scrypt(PRIVATE)','message': " +
                    err.message + "}", 0);
            }
            encrypted = fs.readFileSync(__dirname + "/userDB/" + user + ".json", "utf8");
            return JSON.parse(decrypt(Buffer.from(encrypted), key));
        });
    }

Tried:

1.

I also tried it with cipher.final("binary") and decipher.final("utf8") instead of cipher.final() and decipher.final() (because i read that somewhere) But it also didn't work. I just wanna get this to work and stop googling without finding anything useful, so hopefully you guys know what i have done wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...