[ $davids.sh ] โ€” david shekunts blog

๐Ÿ” Query Encryption

# [ $davids.sh ] ยท message #101

๐Ÿ” Query Encryption

We found a solution, and I want to share it with you:

The task was to add an extra layer of security to help (1) identify the user and (2) verify that the message content was not altered on its way to the server. This is often necessary, for example, when making requests for financial transactions.

One of the simplest options is to use HMAC (used by Yu.Kassa, Tinkoff, Stripe, etc.).

The idea behind HMAC is that the client, after forming a transaction data object, creates a string from the object's values, adds an HMAC secret, and encrypts it. The resulting encrypted string (signature) is added to the request and sent to the server.

The server, upon receiving the request, performs the same operations on its contents using the same HMAC secret and compares it with the signature sent in the request. If they are identical, everything is fine; if not, it means someone tried to replace the package contents or has the wrong key.

The main problem is that we need to store the same HMAC secret, tied to each client (because each client has their own).

It's convenient to store it in a database, but what if the database is stolen?

The solution turned out to be surprisingly simple: instead of storing the HMAC secret in plain text, we will encrypt it when storing it in the database and decrypt it when creating a signature for verification.

The "aes-256-cbc" algorithm is ideal for this. The secrets for it are stored in the application's environment variables.

As a result, even if the database is stolen, the attackers will not be able to decrypt the HMAC secrets, and to do so, they would need access to the application or a memory dump of the application.

In short, encryption is the best way to protect encryption, and that's how it is

P.S.

I've had a coronavirus for 4 weeks now, so I'm not very active ๐Ÿ™ Be careful, as there have been a lot of infections lately, and even with good health, it feels like having a 3rd-degree bronchitis