【问题标题】:encrypt data using aes-128-ecb in nodejs在 nodejs 中使用 aes-128-ecb 加密数据
【发布时间】:2020-09-29 18:05:22
【问题描述】:

我必须在 nodejs 中使用 aes-128-ecb 加密数据,我的代码是

我正在使用 Crypto 来加密数据

const crypto = require('crypto');

const secret = '1000060000000000';

const cipher = crypto.createCipher('aes-128-ecb', secret);

const ciphertext = cipher.update('9', 'utf8', 'base64')+cipher.final('base64');

console.log("Cipher text is: " + ciphertext);

输出应该是EtgITaHs6lEvEHBipj08Kg== 但输出为nNzqejauQBnfiDqznGhZ0Q==

【问题讨论】:

  • 使用crypto.createCipheriv('aes-128-ecb', secret, null) 代替已弃用 createCipher()。后者使用 KDF,这显然不适合您的情况。
  • 安全警告:请不要使用 ECB 模式。至少使用带有随机/不可预测 IV 的操作模式,以便您的加密在语义上是安全的。那么您应该使用也支持身份验证的操作模式,例如 AES-GCM。如果要检测对密文的(恶意)修改,则必须进行身份验证。这很有用,因为许多操作模式都是可延展的。

标签: node.js encryption aes cryptojs


【解决方案1】:

这里的问题是crypto.createCipher的使用,它不直接使用密钥,而是使用摘要。

引用文档:

crypto.createCipher() 的实现使用 OpenSSL 函数 EVP_BytesToKey 派生密钥,摘要算法设置为 MD5,一次迭代,无盐。

另一方面,如果我们使用cipher.createCipheriv,我们可以直接指定密钥,它会给我们预期的输出。

这是一个例子:

const crypto = require("crypto");

function encrypt(plainText, key, outputEncoding = "base64") {
    const cipher = crypto.createCipheriv("aes-128-ecb", key, null);
    return Buffer.concat([cipher.update(plainText), cipher.final()]).toString(outputEncoding);
}

function decrypt(cipherText, key, outputEncoding = "utf8") {
    const cipher = crypto.createDecipheriv("aes-128-ecb", key, null);
    return Buffer.concat([cipher.update(cipherText), cipher.final()]).toString(outputEncoding);
}

const key = "1000060000000000";
const plainText = "9";
const encrypted = encrypt(plainText, key, "base64");
console.log("Encrypted string (base64):", encrypted);
const decrypted = decrypt(Buffer.from(encrypted, "base64"), key, "utf8")
console.log("Decrypted string:", decrypted);

输出将是

EtgITaHs6lEvEHBipj08Kg==

【讨论】:

  • 完全成功,这应该被标记为解决方案
【解决方案2】:

虽然晚了,但会帮助别人 您可以通过任何算法,即 aes-128-cbc , aes-128-ecb

在服务文件夹或 Node.js 应用程序中的任何位置创建一个新文件并将其命名为 aes-service.js

aes-service.js


    const crypto = require('crypto');
    
    const cryptkey = 'C51GH00SE8499727';
    const iv =  'BDA30EGDH1578F81';
    
    
    async function encrypt(text){
        try {
            var cipher = crypto.createCipheriv('aes-128-cbc',cryptkey,iv);
            var crypted = cipher.update(text,'utf8','base64');  //base64 , hex
            crypted += cipher.final('base64');
            return crypted;
        } catch (err) {
            console.error('encrypt error',err);
            return null;
        }
    }
    
    async function decrypt(encryptdata){
        //Check all Algorithms
        console.log(crypto.getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
    
        try {
            let decipher = crypto.createDecipheriv('aes-128-cbc',cryptkey,iv)
            decipher.setAutoPadding(false)
            let decoded  = decipher.update(encryptdata,'base64','utf8') //base64 , hex
            decoded  += decipher.final('utf8')
            return decoded
        } catch (err) {
            console.error('decrypt error',err)
            return null
        }
    }
    
    const AesService = {
        encrypt:encrypt,
        decrypt:decrypt,
    }
    module.exports = AesService

Node.js 控制器,即 abc.controller.js //从node.js请求中获取aes加密数据


    const AesService  = require("./services/aes-service")
    
    exports.getAesEncryptedDatafromReq= async (req, res) => {
       
        try{
            let decryptData = ''
            try{
                const buffers = [];
                for await (const chunk of req) {
                    buffers.push(chunk);
                }
                const dataBuffer = Buffer.concat(buffers).toString();
                const jsonParsedData = JSON.parse(dataBuffer)
                decryptData = jsonParsedData.data
            }catch(err){}
    
           
          
            let decryptedData = await AesService.decrypt(decryptData)
            console.log('decrypted data',decryptedData)
    
            let sendbackdata = {
                "status": 0,
                "anotehr_key":[
                    { "dec":"0", "asc":"1"}
                ]
            }
            sendbackdata = JSON.stringify(sendbackdata)
            let encryptedData = await AesService.encrypt(sendbackdata)
            
              //Check if encrypted performed well
             // let decryptedDataAgain = await AesService.decrypt(encryptedData)
            //console.log('decryptedDataAgain ',decryptedDataAgain)
    
    
            return res.status(201).send({"data":encryptedData})
    
        }catch(err){
            return res.status(500)
        }
    }

添加路线

 router.post("/get/aes/encrypted/data/from/req", controller.getAesEncryptedDatafromReq)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多