简体   繁体   English

NodeJS Crypto randomBytes转换为字符串的十六进制加倍大小

[英]NodeJS Crypto randomBytes to string hex doubling size

I'm experiencing an odd issue using NodeJS crypto and the crypto.randomBtyes function. 使用NodeJS crypto和crypto.randomBtyes函数遇到一个奇怪的问题。 I've detected strange behaviorthat seems to have only recently appeared in my NodeJS / Typescript 3.2 application. 我检测到奇怪的行为,似乎只是最近才出现在我的NodeJS / Typescript 3.2应用程序中。

The error makes sense in its own right: Invalid key length at Cipheriv.createCipherBase (internal/crypto/cipher.js:79:18) 该错误本身具有说服力:Cipheriv.createCipherBase的密钥长度无效(内部/密码/cipher.js:79:18)

Upon inspecting the key length returned, it is doubling the requested number of bytes. 检查返回的密钥长度后,它会将请求的字节数加倍。 I stated this as "odd" in that it was working previously (as of Thursday/Friday last week (3/7/2019 - 3/8/2019) but as of this morning the new behavior was detected. However, I haven't run any updates since so hopefully I'm missing something obvious. I could change my key size to be half of what I want, however, I wanted to see if I'm overlooking something simple before I implement a hack. 我将其表示为“奇数”是因为它之前(截至上周四/周五(2019年3月7日至2019年3月8日)有效),但截至今天上午,已检测到新行为。但是,我还没有可以运行任何更新,因为我希望我遗漏了一些明显的东西,我可以将密钥大小更改为所需大小的一半,但是,我想看看在实施hack之前是否忽略了一些简单的事情。

Here is a fairly basic example of my crypto implementation. 这是我的加密实现的相当基本的示例。

import crypto = require('crypto');

export class Encryption {
    static GenerateRandomBytesToHex(size: number): string {
        return crypto.randomBytes(size).toString('hex');
    }
}

However when calling: 但是,在致电时:

let cipherKey = Encryption.GenerateRandomBytesToHex(32);

It is returning a 64 character string rather than a 32 character string. 它返回的是64个字符串而不是32个字符串。

Example: c8a8437677fcfab679f92c8470ffc34b932f5aaa3296c09f652d2becfe1db8b2 (64 characters in length) 示例:c8a8437677fcfab679f92c8470ffc34b932f5aaa3296c09f652d2becfe1db8b2(长度为64个字符)

This is an implementation of the concepts outlined in this article: http://vancelucas.com/blog/stronger-encryption-and-decryption-in-node-js/ 这是本文概述的概念的实现: http : //vancelucas.com/blog/stronger-encryption-and-decryption-in-node-js/

Any help would be greatly appreciated. 任何帮助将不胜感激。

GenerateRandomBytesToHex function returns you a hash that is X Byte long inside of a String where each Byte is displayed in hexadecimal value. GenerateRandomBytesToHex函数返回一个散列,该散列在String内部为X字节长,其中每个字节以十六进制值显示。

The hexidecimal value of the number 42 is 0x2A . 数的十六进制值420x2A You can see that one Byte (from 0 to 254) is displayed using 2 character in hexadecimal. 您可以看到一个字节(从0到254)以十六进制2个字符显示。 So it's normal that 32 Byte get displayed as 64 character. 因此,通常将32字节显示为64个字符。


Exemple : https://codebeautify.org/string-hex-converter 范例: https//codebeautify.org/string-hex-converter

在此处输入图片说明

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

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