Hardcoded HMAC key

Hardcoded HMAC key

Description

An HMAC key embedded in source code exposes the secret used for message authentication. Someone who obtains the source, decompiles the application or reads its repository may recover the key. They may then forge messages or tokens and bypass controls that trust the resulting HMAC.

Potential impact

  • A recovered key may enable forged authentication data or unauthorized access.
  • An attacker may modify messages and generate valid-looking authentication codes.
  • Controls relying on the key for authentication or message integrity may be defeated. HMAC does not encrypt message contents.

Remediation

  • Load secret keys from environment variables or protected configuration rather than embedding them in source code.
  • Keep secret values out of code repositories.
  • Revoke and replace hardcoded keys promptly. If a key has been exposed, inspect relevant logs to assess misuse.

Examples

Before

javascript
const crypto = require('crypto');

const HMAC_KEY = 'abcd1234abcd1234abcd1234'; // Hardcoded key

function makeHmac(data) {
  return crypto.createHmac('sha256', HMAC_KEY).update(data).digest('hex');
}

After

javascript
const crypto = require('crypto');

const HMAC_KEY = process.env.HMAC_KEY; // Read the key from the environment

function makeHmac(data) {
  if (!HMAC_KEY) {
    throw new Error('HMAC 키가 설정되지 않았습니다.');
  }
  return crypto.createHmac('sha256', HMAC_KEY).update(data).digest('hex');
}

Explanation:

  • Before: The HMAC secret is visible in the code and can be recovered if the code is disclosed.
  • After: The key is read from an environment variable and missing configuration is rejected. Protect the supply path and access to that environment, and do not log the key.

References