Implement request signing for secure API calls with HMAC signatures and timestamp validation.
You are a security engineer implementing request integrity verification systems.
## CONTEXT
I need to implement request signing for my API.
**Requirements:**
- Security Level: {{SECURITY}}
- Client Types: {{CLIENTS}}
- Replay Protection: {{REPLAY}}
- Key Management: {{KEY_MGMT}}
## TASK
Design request signing system:
### 1. SIGNATURE COMPONENTS
```
StringToSign = HTTP_METHOD + "\n" +
PATH + "\n" +
QUERY_STRING + "\n" +
TIMESTAMP + "\n" +
BODY_HASH
```
### 2. REQUEST HEADERS
```
X-Api-Key: api_key_123
X-Timestamp: 2024-01-15T10:30:00Z
X-Signature: HMAC-SHA256(StringToSign, secret_key)
```
### 3. SIGNATURE GENERATION (Client)
```typescript
function signRequest(request, apiKey, secretKey) {
const timestamp = new Date().toISOString();
const bodyHash = crypto.createHash('sha256')
.update(request.body || '')
.digest('hex');
const stringToSign = [
request.method,
request.path,
request.query,
timestamp,
bodyHash
].join('\n');
const signature = crypto
.createHmac('sha256', secretKey)
.update(stringToSign)
.digest('hex');
return {
'X-Api-Key': apiKey,
'X-Timestamp': timestamp,
'X-Signature': signature
};
}
```
### 4. VERIFICATION (Server)
```typescript
async function verifySignature(req) {
const { apiKey, timestamp, signature } = extractHeaders(req);
// Check timestamp (replay protection)
if (isExpired(timestamp, MAX_AGE)) {
throw new Error('Request expired');
}
// Verify signature
const expectedSig = generateSignature(req, apiKey);
if (!timingSafeEqual(signature, expectedSig)) {
throw new Error('Invalid signature');
}
}
```
### 5. REPLAY PROTECTION
- Timestamp window (5 min)
- Nonce tracking
- Request deduplicationOr press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[{SECURITY][{CLIENTS][{REPLAY][{KEY_MGMT]{
const timestamp = new Date().toISOString();
const bodyHash = crypto.createHash('sha256')
.update(request.body || '')
.digest('hex');
const stringToSign = [
request.method,
request.path,
request.query,
timestamp,
bodyHash
].join('\n');
const signature = crypto
.createHmac('sha256', secretKey)
.update(stringToSign)
.digest('hex');
return {
'X-Api-Key': apiKey,
'X-Timestamp': timestamp,
'X-Signature': signature
}{
const { apiKey, timestamp, signature }{
throw new Error('Request expired');
}{
throw new Error('Invalid signature');
}