'Where should I store my secret key for cryptography?

I am creating an application where users can enter some text and I do not want to store that text as it is in the DB. I am going to encrypt it and then store it. However, the problem I am facing is regarding the security of the encryption key. I don't know how I should store it?. I know it shouldn't be saved in a .js or text file as plain text. I thought of env variables but recently I have been told that it is not best practice. Also thought of encrypting the keys but that would be pointless given how decrypting logic is right there on the server. Can anyone here tell me what the best practice is for storing the key or how there is a better way to store data in such a way that it is secure?



Solution 1:[1]

In the end a key is just binary data. So in principle you haven't really solved anything by encryption with a key, if that key can be accessed just as easily as the message you are encrypting. The difference is that a key can be made harder to access. Otherwise you've just achieved obscurity, not encryption.

Generally to make stuff less accessible you need some help. For instance, you can have a human enter a password, from which you can derive a key. Or you can use a system protected key store and use that. Or you could use a different server with different access conditions to encrypt / decrypt. If you don't need the decryption key in the same process then you could also think about asymmetric encryption, as you would only need the private key for decryption (e.g. in the back office).

Key management is the hard part of cryptography though, and there is definitely no one-size-fits-all solution here, it depends entirely on context. You may not want to use password based encryption if you need the derived key when restarting the server at 3 A.M., to name just an example of a mismatched key management scheme.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maarten Bodewes