gpt4 book ai didi

encryption - nodejs中的AES 256 GCM加密解密

转载 作者:行者123 更新时间:2023-12-02 02:48:28 24 4
gpt4 key购买 nike

我正在 nodejs 中实现一组基本的加密/解密函数,但在解密部分我不断收到以下错误:Error: Unsupported state or unable to authenticate data
到目前为止,这是我的代码:

import crypto from 'crypto'
import logger from './logger'

const ALGORITHM = 'aes-256-gcm'

export const encrypt = (keyBuffer, dataBuffer, aadBuffer) => {
// iv stands for "initialization vector"
const iv = Buffer.from(crypto.randomBytes(12), 'utf8')
logger.debug('iv: ', iv)
const encryptor = crypto.createCipheriv(ALGORITHM, keyBuffer, iv)
logger.debug('encryptor: ', encryptor)
logger.debug('dataBuffer: ', dataBuffer)
return Buffer.concat([iv, encryptor.update(dataBuffer, 'utf8'), encryptor.final()])
}

export const decrypt = (keyBuffer, dataBuffer, aadBuffer) => {
const iv = dataBuffer.slice(0, 96)

const decryptor = crypto.createDecipheriv(ALGORITHM, keyBuffer, iv)
return Buffer.concat([decryptor.update(dataBuffer.slice(96), 'utf8'), decryptor.final()])
}

我的错误发生在解密函数的最后一行。我将 iv 存储为 dataBuffer 的一部分。

提前致谢!

最佳答案

我意识到我在发布的原始代码中犯了几个错误,其中一个错误是@TheGreatContini 所说的切片的大小,它以位而不是字节来完成。尽管如此,我遗漏的最大部分是 authTag,它始终应包含在解密功能设置中。

这是我的工作代码,供将来引用的任何人使用:

import crypto from 'crypto'
import logger from './logger'

const ALGORITHM = 'aes-256-gcm'

export const encrypt = (keyBuffer, dataBuffer, aadBuffer) => {
// iv stands for "initialization vector"
const iv = crypto.randomBytes(12)
const cipher = crypto.createCipheriv(ALGORITHM, keyBuffer, iv)
const encryptedBuffer = Buffer.concat([cipher.update(dataBuffer), cipher.final()])
const authTag = cipher.getAuthTag()
let bufferLength = Buffer.alloc(1)
bufferLength.writeUInt8(iv.length, 0)
return Buffer.concat([bufferLength, iv, authTag, encryptedBuffer])
}

export const decrypt = (keyBuffer, dataBuffer, aadBuffer) => {
const ivSize = dataBuffer.readUInt8(0)
const iv = dataBuffer.slice(1, ivSize + 1)
// The authTag is by default 16 bytes in AES-GCM
const authTag = dataBuffer.slice(ivSize + 1, ivSize + 17)
const decipher = crypto.createDecipheriv(ALGORITHM, keyBuffer, iv)
decipher.setAuthTag(authTag)
return Buffer.concat([decipher.update(dataBuffer.slice(ivSize + 17)), decipher.final()])
}

关于encryption - nodejs中的AES 256 GCM加密解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53269132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com