Encrypt and decrypt JavaScript objects using asymmetric key encryption
npm install object-rsa
Initialize the class with at least a key. Have this in mind:
- Private keys can encrypt and decrypt
- Public keys can only encrypt
import ObjectRSA from 'object-rsa';
const objectRsa = new ObjectRSA({
privateKey: '------',
publicKey: '------'
});
You can create a key pair with the crypto
module:
import crypto from 'crypto';
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const objectToEncrypt = {
number: '4242 4242 4242 4242',
code: '939',
expiration: '12/23'
};
const encryptedObject = objectRsa.encrypt(objectToEncrypt);
encryptedObject
will now look like:
{
number: 'bo3gQCqp96Ksqt47BuVGGj+jpjK4Q5j8mAmv+EgW...',
code: 'DF/pkpCbgRJ61z1pHhH2sps02pN0S2eFY9XI6QFzvmMvN...',
expiration: 'FaAYCvvMvciMcY1AGX2Jaoy2sf5pzaP...'
}
const objectToDecrypt = {
number: 'bo3gQCqp96Ksqt47BuVGGj+jpjK4Q5j8mAmv+EgW...',
code: 'DF/pkpCbgRJ61z1pHhH2sps02pN0S2eFY9XI6QFzvmMvN...',
expiration: 'FaAYCvvMvciMcY1AGX2Jaoy2sf5pzaP...'
};
const decryptedObject = objectRsa.decrypt(objectToDecrypt);
decryptedObject
will now look like:
{
number: '4242 4242 4242 4242',
code: '939',
expiration: '12/23'
}
For now, not every value inside the object is encrypted. Check this list (✅ is encrypted, ❌ is not encrypted):
- Strings ✅
- Objects ✅
- Arrays ✅
- Arrays of objects ✅
- Booleans ❌
- Numbers ❌
We used the package
template using:
npx get-template@latest package