gpt4 book ai didi

javascript - Node.js 中的缓冲区和 URL 编码

转载 作者:行者123 更新时间:2023-11-30 19:17:07 35 4
gpt4 key购买 nike

如何在 Node.js 中对缓冲区进行 url 解码和 url 编码?我有以 url 编码形式传入的密文字节,我需要对它们进行解码和解密,因此不能保证缓冲区具有所有标准 UTF-8 字符。

这是我尝试过的,但解码结果与原始结果不匹配:

> foo = Buffer.from('deadbeef', 'hex')
<Buffer de ad be ef>
> fooEnc = encodeURIComponent(foo)
'%DE%AD%EF%BF%BD%EF%BF%BD'
> fooDec = decodeURIComponent(fooEnc)
'ޭ��'
> Buffer.from(fooDec).toString('hex')
'deadefbfbdefbfbd'

最佳答案

以下是我想出的一些函数,用于在 url 编码和缓冲区之间进行转换(对于任何字节值,包括非标准 utf8):

const isUrlSafe = (char) => {
return /[a-zA-Z0-9\-_~.]+/.test(char)
}

const urlEncodeBytes = (buf) => {
let encoded = ''
for (let i = 0; i < buf.length; i++) {
const charBuf = Buffer.from('00', 'hex')
charBuf.writeUInt8(buf[i])
const char = charBuf.toString()
// if the character is safe, then just print it, otherwise encode
if (isUrlSafe(char)) {
encoded += char
} else {
encoded += `%${charBuf.toString('hex').toUpperCase()}`
}
}
return encoded
}

const urlDecodeBytes = (encoded) => {
let decoded = Buffer.from('')
for (let i = 0; i < encoded.length; i++) {
if (encoded[i] === '%') {
const charBuf = Buffer.from(`${encoded[i + 1]}${encoded[i + 2]}`, 'hex')
decoded = Buffer.concat([decoded, charBuf])
i += 2
} else {
const charBuf = Buffer.from(encoded[i])
decoded = Buffer.concat([decoded, charBuf])
}
}
return decoded
}

示例:

> const buf = Buffer.from('4142432b', 'hex')
> const encoded = urlEncodeBytes(buf)
'ABC%2B'

> const encoded = 'ABC%2B'
> const buf = urlDecodeBytes(encoded)
<Buffer 41 42 43 2b>

关于javascript - Node.js 中的缓冲区和 URL 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57873879/

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