【问题标题】:Cipher and decipher a number into hex in nodejs在nodejs中将数字加密并解密为十六进制
【发布时间】:2022-09-28 01:11:24
【问题描述】:

我正在寻找一种有效的方法来使用相同的密钥对数字进行加密和破译。 这不用于加密或加密任何东西,因此它不需要是安全的。

我有一个唯一的号码,我总是希望从密码中得到相同的结果。密码不应太长(超过 6 个字符)。 我确实关心速度,因为我将制作大约 1000 个/毫秒的密码。

我将寻找密码的最大数字是 100,000,000 并且考虑到字母数字 = 26 个小写字母 + 26 个大写字母和 10 个数字的 6 个字符,大约 5.680 * 10^9 组合就足够了。

伪代码示例:

let num_to_cypher = 1;
let cypher = cypher_this_number(num_to_cypher); // ==> Ax53iw
let decypher = decypher_this_number(cypher); // ==> 1

let num_to_cypher_ex_2 = 12
let cypher_ex_2 = cypher_this_number(num_to_cypher_ex_2); // ==> 2R5ty6
let decypher_ex_2 = decypher_this_number(cypher_ex_2); // ==> 1

编辑1:

我本可以做类似下面的事情,但我不能在这个例子中定义密码的长度,我不关心加密,所以我可以更快地进行。

function encrypt(text){
    let cipher = crypto.createCipher(\'aes128\',\'d6F3Efeq\')
    let crypted = cipher.update(text,\'utf8\',\'hex\')
    crypted += cipher.final(\'hex\');
    return crypted;
}

function decrypt(text){
    let decipher = crypto.createDecipher(\'aes128\',\'d6F3Efeq\')
    let dec = decipher.update(text,\'hex\',\'utf8\')
    dec += decipher.final(\'utf8\');
    return dec;
}

    标签: node.js cryptography hex


    【解决方案1】:

    我会使用一个好的散列函数。这两种算法是相当不错的哈希算法:

    [编辑注意...]

    由于您似乎想要 2 路编码,Base-64 可能是您的朋友。

    这将编码和解码任何 32 位有符号整数值(范围从 -2,147,483,648 到 +2,147,483,647 为 6 个字符。

    const {Buffer} = require('buffer');
    
    const buf = Buffer.alloc(4);
    const pad = [ '' , '', '==' , '=' ];
    
    const MIN_INT32 = -2_147_483_648; // 0x80000000
    const MAX_INT32 = +2_147_483_647; // 0x7FFFFFFF
    
    function encode(n) {
    
        if ( !Number.isInteger(n) || n < MIN_INT32 || n > MAX_INT32 ) {
            throw new RangeError("n must be a valid 32-bit integer such that m is -2,147,483,648 >= m <= +2,147,483,647");
        }
    
        buf.writeInt32BE(n) ;
    
        const b64 = buf.toString('base64').slice(0,-2);
        return b64;
    }
    
    function decode(s) {
        const b64 = s + pad[ s.length % 4 ];
    
        buf.fill(b64, 'base64');
    
        const n = buf.readInt32BE();
        return n;
    }
    

    有了这个,这是一个简单的问题:

    onst n0 = 123_456_789;
    const b64 = encode(n0);
    const n1 = decode(b64);
    
    console.log(`original: ${n0}`  ) ;
    console.log(`encoded:  ${b64}` ) ;
    console.log(`decoded:  ${n1}`  ) ;
    

    产生:

    original: 123456789
    encoded:  B1vNFQ
    decoded:  123456789
    

    【讨论】:

    • 这些是非常好的选择,但我不能在之后“解码”/反转它们。例如,我需要能够解码 FNV1 产生的散列,这至少在合理的性能下是不可能的。
    • @JohnJames——那么 Base-64 编码可能就是你想要的。有关详细信息,请参阅我编辑的答案。
    猜你喜欢
    • 2017-05-07
    • 2015-01-01
    • 2014-02-21
    • 2014-12-23
    • 1970-01-01
    • 2020-12-22
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多