I don't know the specific technology that you are using, so my answer will point in general to the key storage issue.
First, two big remarks:
- Even with some heavy specialized hardware (banks and other critical systems use Hardware Security Modules -HSMs- for this), there is always a risk of getting your key stolen. What you choose to do depends on how important is your key and how much are you willing to do to protect it. I will try to avoid to mention solutions involving hardware, because they are usually overkill for most people.
- There are, however, good practices that you can follow: https://www.owasp.org/index.php/Cryptographic_Storage_Cheat_Sheet
Now, some advise. Whatever you do, don't store your key in plaintext (and much less hardcoded). If you are using public key cryptography, PKCS12 files (usually with extension .p12 or .pfx) are the standard way to store the data. They are usually password protected.
Here you face a problem: if you have a key, you need to use it. If you use the key, it will be in "plaintext", at least in RAM. So, you need a way to enable the access that keeps the key as isolated as possible. If the actions are triggered by a user, things are relatively nice, because you could ask for the password before using the key.
If the actions are automated, however, you need to find a way to store the password. Even security software like some PGP implementations have approaches for this that aren't nice:
- Ask for the password in command line: command -password my-password. This, put in a bat, works. But the password is stored and, depending of the operating system, even available with the command
history
.
- Store it in a file: at least you don't leave copies around, but the password is still in plaintext.
- Encrypt it using system data as encryption key: the password is relatively protected, but you lose portability and an attacker with access to the computer won't be stopped by the control.
- Ask for the password once one the service is on: a bit more reasonable, but not always possible (if the service is critical but just one person has the password, availability might be compromised).
- Fancy things could be done with threshold decryption, but that's probably too much for that case also.
I do not provide details on each option because what you can do probably depends on what your framework allows and the way in which your system is used, but I hope it helps as a reference of the different options. In any case, do not implement any cryptographic functionality on your own. Bad crypto is worse than no crypto at all.