Reputation: 1
I have a field in mongo which is of number type and I want to encrypt it into a unique number to save it and then decrypt it back to the original number without converting it to a string value.
Upvotes: 0
Views: 859
Reputation: 707806
You can create a Buffer object, write a Javascript number to the Buffer (creating a binary set of bytes) and then encrypt the contents of the buffer. Then, save the encrypted binary data from the buffer in your database.
To decrypt, you can reverse the process by reading the binary from the database into a Buffer, decrypt the buffer and then read the number from it.
You can write a Javascript number to a Buffer with something like:
buf.writeDoubleBE(value[, offset])
and there's a complementary method for reading a number from the buffer.
So, this doesn't have to be converted to a string anywhere, but it is converted to a binary Buffer.
FYI, here's an article on encrypting strings, buffers and streams in nodejs: https://attacomsian.com/blog/nodejs-encrypt-decrypt-data
FYI, MongoDB has some built-in encryption options (depending upon what storage engine you're using). This is more like database-level encryption that protects the whole database on disk rather than encrypting individual fields. Here's some info on that: https://docs.mongodb.com/manual/core/security-encryption-at-rest/#std-label-encrypted-storage-engine.
The MongoDB doc also has some info on client-side encrypting of individual fields here: https://docs.mongodb.com/manual/core/security-client-side-encryption/
and here:
https://docs.mongodb.com/manual/core/security-explicit-client-side-encryption/
And, apparently the enterprise version of mongodb 4.2 or later has some automatic field level encryption.
Upvotes: 1