Last Updated: January 20, 2020
·
3.494K
· andrepiper

Node.js User Encryption API

/*
Defining route
*/

exports.register = function (api) {
    api.post('/v1/create', createUser);
};

/*
Therefore route will be ex. https://url/user/v1/create with form-data see below
*/

Picture

function createUser(request,response){

/*
userModel json variable
*/

var userModel={};

/*
getting username and password from post
*/

userModel.username=request.body.username;
userModel.password=request.body.password;

/*
creating salt and cypher password
*/

userModel.salt=createSalt();

    require('crypto').randomBytes(48, function(ex, buf) {
    userModel.token = buf.toString('base64');
    });
    var clearText=userModel.password;
    hash(clearText,userModel.salt,function(err, crypted) {
    var cypherText=crypted;
    userModel.password=cypherText;

 /*
Do whatever with username,password and salt, more than likely store in a database
*/

     response.send(200, { success :'User encrypted'});
    });

/*
HELPER FUNCTIONS BELOW
*/

var crypto = require('crypto');
var iterations = 1000;
var bytes = 32;

function createSalt() {
    return new Buffer(crypto.randomBytes(bytes)).toString('base64');
}

function hash(text, salt, callback) {
    crypto.pbkdf2(text, salt, iterations, bytes, function(err, derivedKey){
        if (err) { callback(err); }
        else {
            var h = new Buffer(derivedKey).toString('base64');
            callback(null, h);
        }
    });
}

function zumoJwt(aud, userId, masterKey) {

    function base64(input) {
        return new Buffer(input, 'utf8').toString('base64');
    }

    function urlFriendly(b64) {
        return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(new RegExp("=", "g"), '');
    }

    function signature(input) {
        var key = crypto.createHash('sha256').update(masterKey + "JWTSig").digest('binary');
        var str = crypto.createHmac('sha256', key).update(input).digest('base64');
        return urlFriendly(str);
    }


    var s1 = '{"alg":"HS256","typ":"JWT","kid":0}';
    var j2 = {
        "exp": new Date().setUTCDate(new Date().getUTCDate() + 4000),
        "iss":"urn:microsoft:windows-azure:zumo",
        "ver":1,
        "aud":aud,
        "uid":userId 
    };
    var s2 = JSON.stringify(j2);
    var b1 = urlFriendly(base64(s1));
    var b2 = urlFriendly(base64(s2));
    var b3 = signature(b1 + "." + b2);
    console.log('jwt: ', [b1,b2,b3].join("."));
    return [b1,b2,b3].join(".");
}

function slowEquals(a, b) {
    var diff = a.length ^ b.length;
    for (var i = 0; i < a.length && i < b.length; i++) {
        diff |= (a[i] ^ b[i]);
    }
    return diff === 0;
}

1 Response
Add your response

Will make next tip geared towards azure.

over 1 year ago ·