Trying to add data in unsupported state at Cipher.update

后端 未结 2 1708
暖寄归人
暖寄归人 2021-01-12 19:11

Below code is working

var crypto = require(\'crypto\');
var cipher = crypto.createCipher(\'aes-128-cbc\',\'abcdefghijklmnop\')
var http = require(\'http\')

         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-12 20:01

    Check this out

    Thats mainly because every time we run the encrypt or decrypt we should repeat crypto.createCipher('aes192', secrateKey); and crypto.createDecipher('aes192', secrateKey);

    let secrateKey = "secrateKey";
    const crypto = require('crypto');
    
    
    function encrypt(text) {
        encryptalgo = crypto.createCipher('aes192', secrateKey);
        let encrypted = encryptalgo.update(text, 'utf8', 'hex');
        encrypted += encryptalgo.final('hex');
        return encrypted;
    }
    
    function decrypt(encrypted) {
        decryptalgo = crypto.createDecipher('aes192', secrateKey);
        let decrypted = decryptalgo.update(encrypted, 'hex', 'utf8');
        decrypted += decryptalgo.final('utf8');
        return decrypted;
    }
    
    let encryptedText = encrypt("hello");
    console.log(encryptedText);
    
    let decryptedText = decrypt(encryptedText);
    console.log(decryptedText);
    

    Hope this helps!

提交回复
热议问题