Search code examples
node.jsrandomcryptojs

Nodejs generate secure random characters not including given chars


I was reading about generating secure random generator in nodejs. I tried this and works well to generate secure random characters.

const crypto = require('crypto');

var length = 22
var generated = crypto.randomBytes(Math.ceil(length / 2))
                      .toString('hex').slice(0, length);
//it returned "14cf777d3ca307f5e78496"

How can I generate secure random characters not including given pattern in nodejs. Ex: ['a', '2'], it should return secure chars without given pattern 14cf777d3cr307f5e78496


Solution

  • The crypto module does not offer directly what you are looking for. Although, what you can do, is to keep recursively generating your crypto until none of the patterns are found inside.

    For that, you can use the following:

    async function generateRandomCrypto(length, patterns) {
        const generated = await crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
    
        let isValid = true;
        for (pattern of patterns) {
            if (generated.indexOf(pattern) !== -1) {
                isValid = false;
                break;
            }
        }
    
        if (!isValid) {
            return await generateRandomCrypto(length, patterns);
        }
    
        return generated;  
    }
    

    Now, the function will keep generating until it finds one that does not include any of the strings provided in the patterns array.

    If you are somehow worried about any kind of performance impact - there is no need to.

    Assuming your patterns are not single letter strings, it is very unlikely that they will appear in the random sequence - thus, the generation might run only once.

    And even if, I did a test for you - I ran this with a patterns array looking like that:

    const patterns = ['a', 'b'];
    

    And I had 4 - 8 function executions on average.