Blog | G5 Cyber Security

Secure Code Credentials

TL;DR

Never hardcode passwords or API keys directly into your code. Use environment variables, a secrets manager (like HashiCorp Vault, AWS Secrets Manager, or Azure Key Vault), or dedicated configuration files that are not checked into version control.

Why You Shouldn’t Hardcode Credentials

Hardcoding credentials is a major security risk:

How to Store Credentials Securely

  1. Environment Variables
    • What they are: Key-value pairs set outside of your application’s code, accessible at runtime.
    • How to use them: Most programming languages provide ways to access environment variables.
      # Python example
      import os
      api_key = os.environ.get('MY_API_KEY')
      password = os.environ.get('DATABASE_PASSWORD')
    • Setting them: How you set environment variables depends on your operating system and deployment environment (e.g., using export in Linux/macOS, or setting them through a control panel in cloud providers).
  2. Secrets Managers
    • What they are: Dedicated services for storing and managing sensitive data like passwords, API keys, and certificates. They offer features like encryption, access control, auditing, and versioning.
    • Popular options: HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, Google Cloud Secret Manager.
    • How to use them (example with AWS Secrets Manager):
      1. Store your secret in AWS Secrets Manager.
      2. Grant your application the necessary permissions to access the secret.
      3. Use the AWS SDK to retrieve the secret at runtime.
        # Python example using boto3
        import boto3
        
        client = boto3.client('secretsmanager')
        secret_name = 'my-database-credentials'
        response = client.get_secret_value(SecretId=secret_name)
        secret = json.loads(response['SecretString'])
        password = secret['password']
  3. Configuration Files (with caution)
    • What they are: Separate files containing application settings, including credentials.
    • Important: Never commit these files to version control! Use a .gitignore file to exclude them.
      # .gitignore example
      config.ini
      secrets.json
    • Encryption: If you must use configuration files, encrypt them at rest and in transit.

Best Practices

Exit mobile version