I am trying to encrypt an object that is a JSON, in order to do so first i convert it to String, encrypt it and when is decrypted it cames back as random simbols because it is unable to convert it.
I try to encrypt:
{ a: 'A',
L: 'GET ALL USERS',
Po:
{ ttp: 'localhost:3000/ttp/allusers',
b: 'localhost:8000/server/allusers',
Mhash: '6d2e5cc3a67ae82ae7edf6fb6054f977' } }
var mensajeToBbignum = bignum.fromBuffer(new Buffer(x));
console.log('\n\n\nCleartext:',
mensajeToBbignum.toBuffer().toString(),'\n');
var mensajeToBcrip = keys2.publicKey.encrypt(mensajeToBbignum);
console.log('encryption with public:', '\n',
mensajeToBcrip.toBuffer().toString('base64'), '\n');
From String to encryption i have the following:
{"a":"A","L":"GET ALL USERS","Po":{"ttp":"localhost:3000/ttp/allusers","b":"localhost:8000/server/allusers","Mhash":"6d2e5cc3a67ae82ae7edf6fb6054f977"}}
And finally encoded in base64:
augf1Fuv2GwOYy0aipv1u6LZ3nWvGVz4M9JoA8uhlJgbuoGtYxe0GLSW+u6s1/kiOIqeF0s0cmCFgzpj/oKdF+0k9+OC/TVBgmk+1mO19pWnhcfS42j5OKPpy27mx0tRymQcS7TVDDsak2JptEv7O3POAvWVAKZRJ13zGMwP4qU=
I know it receives the same string in base64 with this code:
var recibidoBignum = bignum(req.body.mensaje);
console.log('recibidoBignum:', '\n',
recibidoBignum.toBuffer().toString('base64'), '\n');
var reqdecrip = keys.privateKey.decrypt(recibidoBignum);
console.log('decryption with private:', '\n', reqdecrip.toBuffer().toString(), '\n\n\n\n\n\n');
And the following logs:
encryption with public:
augf1Fuv2GwOYy0aipv1u6LZ3nWvGVz4M9JoA8uhlJgbuoGtYxe0GLSW+u6s1/kiOIqeF0s0cmCFgzpj/oKdF+0k9+OC/TVBgmk+1mO19pWnhcfS42j5OKPpy27mx0tRymQcS7TVDDsak2JptEv7O3POAvWVAKZRJ13zGMwP4qU=
decryption with private:
�8����P�`��t�> �x)���m��S���n�l� �:�17^�����l�}%��綷K�N�Y�a-5��J���p���8�@�b�Vs�
So it seems it can encrypt a JSON object but then is unable to decrypt it
The only external module used is bignum, the rsa implementation is the following
rsa = {
publicKey: function(bits, n, e) {
this.bits = bits;
this.n = n;
this.e = e;
},
privateKey: function(p, q, d, publicKey) {
this.p = p;
this.q = q;
this.d = d;
this.publicKey = publicKey;
},
generateKeys: function(bitlength) {
var p, q, n, phi, e, d, keys = {};
// if p and q are bitlength/2 long, n is then bitlength long
this.bitlength = bitlength || 2048;
console.log("Generating RSA keys of", this.bitlength, "bits");
p = bignum.prime(this.bitlength / 2);
do {
q = bignum.prime(this.bitlength / 2);
} while (q.cmp(p) === 0);
n = p.mul(q);
phi = p.sub(1).mul(q.sub(1));
e = bignum(65537);
d = e.invertm(phi);
keys.publicKey = new rsa.publicKey(this.bitlength, n, e);
keys.privateKey = new rsa.privateKey(p, q, d, keys.publicKey);
return keys;
}
};
rsa.publicKey.prototype = {
encrypt: function(m) {
return m.powm(this.e, this.n);
},
decrypt: function(c) {
return c.powm(this.e, this.n);
}
};
rsa.privateKey.prototype = {
encrypt: function(m) {
return m.powm(this.d, this.publicKey.n);
},
decrypt: function(c) {
return c.powm(this.d, this.publicKey.n);
}
};
module.exports = rsa;