Node.js crypto publicEncrypt returns 值太长

Node.js crypto publicEncrypt returns a too long value

我正在尝试从 iOS 设备(在 swift 中)生成的 RSA Public 密钥加密字符串。 我正在使用 crypto.publicEncrypt 函数,但是 base64 字符串 returned 对于密钥来说太长了。

在我的例子中,是一个 3072 位的 RSA 密钥,所以预期的加密值长度是 384 字节,但是 crypto.publicEncrypt() return 512.

我确实尝试了此功能的每个选项以及客户端的每个修改。我很确定问题出在加密上,因为客户端可以使用相同的密钥进行加密。

如果有人能拯救我的周末!?

我的代码:

// Dependencies
const crypto = require('crypto')

// The secret data
const message = Buffer.from("Secret message")

// Secret data encryption
const publicKey // Buffer from Binary Data of the public key, in PEM format
const pem = publicKey.toString('utf8')
const opts = {
    key: pem, // Public key
    oaepHash: 'RSA-SHA384', // Algorithm used by the client
    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING // Every other paddings throw an exception
}
var bufferEncryption = crypto.publicEncrypt(opts, message)
const encryptedMessage = bufferEncryption.toString('base64')

// Sending encryptedMessage to the client...

// My issue
console.log(encryptedMessage.length) // 512 (expected: 384)

已解决: 代码没问题。加密函数具有预期的行为。我的错误来自对客户端的响应编码。 我混淆了预期的字节和字符。同时使用不同语言工作的乐趣。 感谢@Maarten Bodewes 为我解惑。

我不确定您为什么期望密钥是 384 个字符。 Base 64 使用 4 个字符编码 3 个字节(或每个字符 6 位,毕竟 2^6=64)。如果我们假设相同数量的字节 - 对于 US-ASCII 兼容方案,例如 Windows-1252 或实际上是 UTF-8 - 那么 (384 / 3) * 4 = 512。你所说的字节大小是大小没有对文本进行任何编码

这里还有另一个答案表明您可以使用 。除非我大错特错,否则它将转换为字节数组的模拟。