How to Store API Credentials
How to keep secrets while keeping peace of mind?

IT history is plastered with failures to keep secrets, such as when millions of user names and passwords were offered for sale on a shady dark web site. Storing credentials is more difficult than it appears.
I recently had to solve a variant of this task. While integrating a shipping service into an e-commerce site I stumbled onto the simple question: how to store the API credentials of the shipping service in the shop database?
The challenge is that we can’t use hashing, as we would do for user passwords (this excellent article explains in detail why hashing is the only safe option for user passwords). We need the credentials to access the API, hence we need to reveal them upon retrieval from store — as shown simplified in the pic below.

One solution
Encryption comes to mind. AES-256 bit encryption is deemed today as state of the art because trying out all keys until you get the right one might take great resources and a long time. Encryption alone has its risks, however. In the simplest case, a mindless user chooses the word “password” for the password and suddenly the potential hacker may have an easier task because they only need to try until password is revealed.
One way to circumvent this problem is to obfuscate the credentials before encrypting them. That can be done very easily and fast.
The idea is simple: let’s spread the credentials characters among a larger string —like spreading some pepper in a plate of salt.
We insert consecutively each character from the input crds
between every Nth byte of saltCredentials
and pay attention to make the latter long enough to host the full input. We also need to keep the length of the original and the step increase for the reverse extraction. We store this info in the first two bytes of the resulting payload before encrypting it.
The reverse process is equally simple. We decrypt first before extracting the meta info from the first two bytes from the payload. Then loop extracting the original pepper from the salt.
Is this hackerproof? No. If a hacker is intended to spend resources on cracking your scheme, they will manage. Will it make it more difficult? Probably, especially because they won’t be able to tell which decryption key is the right one. The final bit is then to hide the software, which can be done easily by encapsulating it with a php
wrapper.
BTW: There are many other ways to obfuscate text. The one above is an extreme simplification and we show it here just to inspire you to come up with your own solutions. Happy puzzling!
The full code is on GitHub. Comments and improvements are welcome.
Thank you for reading. I hope this was interesting.
More content at plainenglish.io