简体   繁体   English

Node.js crypto publicEncrypt 返回过长的值

[英]Node.js crypto publicEncrypt returns a too long value

I'm trying to encrypt a string from an RSA Public key, generated by an iOS device (in swift).我正在尝试从由 iOS 设备(快速)生成的 RSA 公钥加密字符串。 I'm using crypto.publicEncrypt function, but the base64 string returned is too long for the key.我正在使用 crypto.publicEncrypt function,但返回的 base64 字符串对于密钥来说太长了。

In my case, is a 3072 bits RSA key, so the expected encrypted value length is 384 bytes, but crypto.publicEncrypt() return 512.就我而言,是 3072 位 RSA 密钥,因此预期的加密值长度为 384 字节,但 crypto.publicEncrypt() 返回 512。

I did try every options for this function and every modifications in the client side.我确实尝试了这个 function 的所有选项以及客户端的所有修改。 I'm pretty sure the problem comes from the encryption, because the client can encrypt with the same key.我很确定问题来自加密,因为客户端可以使用相同的密钥进行加密。

If someone can save my week end??如果有人可以拯救我的周末?

My code:我的代码:

// 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)

SOLVED: No problem with the code.解决:代码没有问题。 The encryption function has the expected behaviour.加密 function 具有预期的行为。 My mistake cames from the response encoding to the client.我的错误来自对客户端的响应编码。 I confused the expected bytes and the characters.我混淆了预期的字节和字符。 The joy to work with different languages in the same time.同时使用不同语言工作的乐趣。 Thank to @Maarten Bodewes for clearing up my confusion.感谢@Maarten Bodewes 解决了我的困惑。

I'm not sure why you expect the key to be 384 characters.我不确定为什么您希望密钥是 384 个字符。 Base 64 uses 4 characters to encode 3 bytes (or 6 bits per character, 2^6=64 after all). Base 64 使用 4 个字符来编码 3 个字节(或每个字符 6 位,毕竟 2^6=64)。 If we assume the same amount of bytes - for US-ASCII compatible schemes such as Windows-1252 or indeed UTF-8 - then (384 / 3) * 4 = 512. The byte size you are talking about is the size without any encoding to text .如果我们假设相同数量的字节 - 对于 US-ASCII 兼容方案,例如 Windows-1252 或 UTF-8 - 那么 (384 / 3) * 4 = 512。您所说的字节大小是没有对文本进行任何编码的大小.

There is another answer here that indicates that you could use binary as encoding .这里还有另一个答案表明您可以使用binary作为编码 Unless I'm terribly mistaken that will convert to an analogue of a byte array.除非我大错特错,否则它将转换为字节数组的类似物。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM