Nodejs decrypt using crypto error wrong final block length

后端 未结 2 1226
有刺的猬
有刺的猬 2020-12-04 03:15

I use this code to crypt/decrypt string value

var crypto = require(\'crypto\');

function encrypt(text){
    var cipher = crypto.createCipher(\'aes-256-cbc\'         


        
2条回答
  •  盖世英雄少女心
    2020-12-04 03:44

    I also faced the same issue. I had to go through all the comments to check for answer and @Alexey Ten's comment helped me. So in order to make @Alexey Ten's answer more visible below are the changes.

    var crypto = require('crypto');
    
    function encrypt(text){
      try{
        var cipher = crypto.createCipher('aes-256-cbc','secret key');
        var encrypted = cipher.update(text.toString(),'utf8','hex') + cipher.final('hex');
        return encrypted;
        } catch(exception) {
          throw exception;
        }
    }
    
    function decrypt(text){
    try{
        var decipher = crypto.createDecipher('aes-256-cbc','secret key');
        var decrypted = decipher.update(text.toString(),'hex','utf8') + decipher.final('utf8');
        return decrypted ;
      } catch(exception) {
         throw exception;
       }
    }
    

提交回复
热议问题