Search code examples
node.jssessionencryptionexpress-sessioncryptico

Saved RSA private key in session, but it has been spoiled


This is what I planned to do.

  1. Generated RSA private/public key when user call my website
  2. Give public key to browser
  3. Save private key in session (node.js, express-session)
  4. When user try to log-in use public key to encrypt id and pw, decrypt it with private key I saved in session

And here comes the problem. I saved private key like this way

app.get('/', function(req, res) {
var passPhrase = 'secret key';
bits = 1024;
req.session.rsa = cryptico.generateRSAKey(passPhrase, bits);
....
}

and RSA key seems quite long, I attached image -> RSA that I generated first(image)

But when I call RSA key from session in another AJAX, suddenly it becomes shorter and I can't decrypt the message because there is a error and it says 'your private key doesn't match with public key'

app.post('/login', function(req, res) {
console.log(req.session.rsa);
}

RSA that I loaded from the session in app.post('/login')

Because of this problem I can't use RSA private/public key to encrypt/decrypt id/pw. Why does it happens? Why data in req.session has been spoiled? I can't understand why value of in it changes.

This is setting of express-session. Is there a problem in here? or any other reason?

app.use(session({
store: new RedisStore({
    host: 'localhost',
    port: 6379,
    client: redis,
    resave: false
}),
secret: 'keyboard cat',
cookie: {
    maxAge: 1000 * 60 * 60
},
resave : false,
saveUninitialized : true

}));

Solution

  • It doesn't seem to be well-documented, but try this:

    // storing the key in the session
    req.session.rsa = JSON.stringify(cryptico.generateRSAKey(passPhrase, bits).toJSON());
    
    // retrieving the key from the session
    let RSAKey = cryptico.RSAKey.parse(req.session.rsa);