【问题标题】:Decrypt the crypto data解密加密数据
【发布时间】:2021-04-22 10:33:54
【问题描述】:

我正在尝试使用节点内置模块加密来加密和解密值。我已经按照tutorial 对数据进行了加密。他们没有提供任何示例代码来解密。当我尝试使用其他教程代码来解密数据时。它不工作。请帮帮我,

代码

const crypto = require('crypto');
  
// Difining algorithm
const algorithm = 'aes-256-cbc';
  
// Defining key
const key = crypto.randomBytes(32);
  
// Defining iv
const iv = crypto.randomBytes(16);
  
// An encrypt function
function encrypt(text) {
  
 // Creating Cipheriv with its parameter
 let cipher = crypto.createCipheriv(
      'aes-256-cbc', Buffer.from(key), iv);
  
 // Updating text
 let encrypted = cipher.update(text);
  
 // Using concatenation
 encrypted = Buffer.concat([encrypted, cipher.final()]);
  
 // Returning iv and encrypted data
 return encrypted.toString('hex');
}


var op = encrypt("Hi Hello"); //c9103b8439f8f1412e7c98cef5fa09a1

【问题讨论】:

  • 添加了答案,希望对您有所帮助。干杯队友

标签: javascript node.js typescript cryptojs


【解决方案1】:

由于您没有提供解密代码,因此无法帮助您实际做错了什么,除此之外您可以这样做来获取解密代码:

const crypto = require('crypto')

// Defining key
const key = crypto.randomBytes(32)

// Defining iv
const iv = crypto.randomBytes(16)

// An encrypt function
function encrypt(text) {
  // Creating Cipheriv with its parameter
  const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv)

  // Updating text
  let encrypted = cipher.update(text)

  // Using concatenation
  encrypted = Buffer.concat([encrypted, cipher.final()])

  // Returning iv and encrypted data
  return encrypted.toString('hex')
}

var op = encrypt('Hi Hello')
console.log(op)

function decrypt(data) {
  // Creating Decipheriv with its parameter
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv)
  // Updating text
  const decryptedText = decipher.update(data, 'hex', 'utf8')
  const finalText = decryptedText + decipher.final('utf8')
  return finalText
}

var decrptedData = decrypt(op)
console.log(decrptedData)

【讨论】:

    猜你喜欢
    • 2013-09-18
    • 1970-01-01
    • 2011-03-12
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 2016-04-25
    相关资源
    最近更新 更多