A few days ago I went to the “Security and login” page of facebook. And I noticed that they store our devices so that we can control what devices are using our facebook accounts.
And I thought “Maybe I can create something like this”.
So I created a new Node.js env and started coding.
My idea is, imagine that the user already has some devices on the database, so I decided to encrypt them to be safer.
Then when I make a request to the database to get an array of all the user_devices that are stored it should look like this:
const user_devices = [ "972f2e0f09e944af2a51aae0608af08b", "1046f21afeda72b832a06dbcb3c713d5", "98905cfb376ceea05026cca6d46a660e" ];
Then I want to do a foreach loop to Decrypt all of them so that they look like this:
const user_devices = [ "127.0.0.1", "127.0.0.2", "127.0.0.3" ];
And then I can use an if statement to validate if the user device that is currently trying to access user account is already saved in the user_devices array.
If it doesn’t, I will get the current user device trying to access the account and I will encrypt it and save it to the user_devices array.
I hope you liked the story and I am doing this to challenge myself 😅.
But I got this error:
internal/crypto/cipher.js:164 const ret = this._handle.final();
And I don’t know what to do now 😩.
Here is the code: https://codesandbox.io/s/facebook-security-login-clone-s0y71?file=/src/index.js:148-286
Advertisement
Answer
You need to use the same IV when you encrypt and decrypt. At the same time, an IV is useless if it’s always the same one. Best practice is:
- Create a new IV everytime you need to encrypt a new string
- Attach the IV to the encrypted string (maybe just concatenate them) and store the result
When you need to decrypt:
- Separate the IV and the encrypted string again
- Decrypt the string using the key and the IV you just separated