Introduction
All mobile apps interact with servers in one way or another — sending requests for data, making form submissions, processing payments. While being a pathway of data exchange, this interaction can also pose as an entry point for hackers to enter in between and gain illegal access to Application’s data or the server data. One such case of hackers infiltrating the resources, is related to weak API verification step. If your API verifies the API key just by checking whether it is present in a header of the request, you are one step away from a spoofed request. This is where HMAC (Hash-based Message Authentication Code) comes into picture.
The following blog post is devoted to HMAC and will cover what HMAC is, why it is important for securing your API, and how to use it in Flutter application.
What Is HMAC, Really?
HMAC in simple terms is used to prove two things simultaneously: that the request sent by the application is attached with a common secret key , and that during transmission the request sent by the Application is not tampered. So it uses a cryptographic hash function (commonly SHA-256) with a secret key to produce a fixed-length signature.
The core idea is simple:
signature = HMAC(secret_key, message)
The application creates a signature using the available information from the request (endpoint, timestamp, body, etc) and a secret key kept secret between the client and the server. The server then recalculates the signature without relying on the application side and compares it with the previous signature. If they both match, the request is not altered and is genuine. If the payload is modified by an attacker even by a single character, the signature will not match and the server will reject the request.
As opposed to the simple API key passed in the header, the HMAC signature is dependent on the content of each particular request. Obtaining the signature of one particular request will not allow an attacker to create another, since they don’t have the secret key needed to generate a new valid signature.
Why Flutter Apps Need This
Mobile applications have a perceived notion of lack of trust as they are working on devices outside of the developers control, and an attacker can decompile the app, intercept requests via a proxy, or replay them. HMAC is useful in mitigating multiple potential attacks like:
- Request tampering — an attacker modifying a request body mid-transit can be intercepted immediately.
- Replay attacks — combined with timestamps or nonces, the old captured requests become useless.
- Basic request forgery — without the shared secret key, generating a valid signature is of no use.
While doing development with this approach, due diligence should also be given about what HMAC cannot solve. The secret key will not be protected if someone tries to reverse engineer the binary of the application and HMAC cannot replace TLS. but it can be used to make it harder for attackers by serving as an additional security layer.
Setting Up the Flutter Project
First we need to add these packages to pubspec.yaml:

Packages required to setup Project
Run flutter pub get to fetch them.
Building the HMAC Signature Generator
The crypto package has all the hashing and HMAC functionality you need. To keep the implementation loosely coupled and hence easier to maintain, we can split the logic into two small, focused classes: one that deals with the raw hashing/HMAC operations and another that deals with constructing the exact string that needs to be signed. Separating these concerns will also lead to better testability, readability and make it easier to change / extend either half without affecting the other.
- HmacService — This is a thin wrapper used so the entire App avoids directly touching the crypto package

Wrapper class to wrap the crypto package
- SignatureGenerator — Used to build the canonical string which both client and server must create identically, and then signs it:

Uses the wrapper class function to create signature
When hashing the body separately (instead of just concatenating it in raw form into the canonical string), the eventual shape of the string is predictable and bounded, regardless of payload size. Hashing the body separately also avoids subtle bugs that may arise from newlines or other delimiter characters inside the body piggybacking off the canonical string’s own separators.
Integrating HMAC into API Requests
Modifying the signature generator into one you actually attach to a request takes three more pieces: a small config object holding your secret key and the header names, a nonce generator for replay protection, and a signer that will pull the timestamp, nonce, canonical string, and signature together into headers.
- Config — secret key, algorithm, and header names in one place:

Config file holding secret key and header names
- Nonce generator — a random, single-use token so a captured request can’t just be replayed, even within the timestamp window:

Creates a number which prevents replaying requests
- Request signer — this is where it all comes together:

RequestSigner class in Dart generating an HMAC-SHA256 signature and attaching signed headers to a request.
This is how the whole process works: each invocation of sign() generates a new timestamp and nonce, combines those along with the hash of the path/method/body and signs it, and returns a headers map. Add that map to any HTTP request, using any HTTP client:
import 'package:http/http.dart' as http;
final signer = RequestSigner();
final path = '/v1/orders';
final body = '{"itemId":"sku_9981","quantity":2}';
final headers = signer.sign(method: 'POST', path: path, body: body);
headers['Content-Type'] = 'application/json';
final response = await http.post(
Uri.parse('https://api.example.com$path'),
headers: headers,
body: body,
);
print('Order placed: ${response.body}');
Here, in the real-world application, such actions would be performed by interceptors, either by using Interceptor provided by Dio itself or using http.Client decorator, so that signing could be automatically performed for all the requests without having to call sign() explicitly every time.
Verifying the Signature on the Server
The server-side implementation also requires mirroring the same architecture, which includes hashing the body individually and folding the nonce into the canonical form. Here is an example using Node.js/Express for you to get a glimpse of both ends of the handshake:

Verifying the Signature on the Server
The following three elements are important in addition to the signature verification process: the time period during which the timestamp is fresh, ensuring that nonces are tracked in order to avoid replay attack within that period, and the usage of constant time equality comparison (timingSafeEqual) function rather than ===, which prevents timing attacks that could leak information about the expected signature byte by byte.
Best Practices and Common Pitfalls
- Not hardcoding the secret key in the app’s source. Anything attached with the binary can be extracted. The Secret Key shall be fetched at the runtime from a secure backend after the authentication process, or use of platform-level secure storage (flutter_secure_storage) once the key is obtained shall be used to have a secured communication.
- Including a timestamp or nonce in the signed payload. Including an identifier like a timestamp for the payload helps to execute an action at the uniquely-requested time. Without one, a captured request can be replayed indefinitely.
- Signing the full request context, not restricting just to the body — also including the method and path of the request. Restricting the sign only to the body enables an attacker to redirect a valid signature to a different endpoint.
- Use of HTTPS protocol regardless – On one hand, HMAC protects integrity and authenticity, while HTTPS provides confidentiality. Combining both vastly improves the security of the request.
- Keeping payload construction identical on both ends – Most common source of “valid request, invalid signature” bugs are mismatched field order or an encoding issue. Logging the exact string which is being signed on both sides when debugging.
Source Code
I’ve published the full working demo on GitHub — it includes a Dio interceptor that automatically signs requests, tamper demos, and a simulated backend verifier: Flutter Demo clone away, and have a look around.
Conclusion
HMAC provides a simple and effective mechanism for covering the legitimacy and integrity of the messages sent by the Mobile application, underpinned by just a shared key and a hashing function. HMAC alone cannot provide defence against all types of attacks, but when combined with TLS, short lived timestamps and proper key handling, it can provide significant protection against message tampering and replay attacks – without having extended lines of code.
For scenarios of developing software which deal with money transfers, personal information or sensitive operations, this protection protocol shall be implemented as a procedure rather than an optional tool.