constant-time-analysis

Analyze cryptographic code to detect operations that leak secret data through execution timing variations.

31,392 stars
Complexity: easy

About this skill

The Constant-Time Analysis skill empowers AI agents to perform critical security audits on cryptographic code. It meticulously examines code for operations that might exhibit timing variations based on the values of secret data (like keys or tokens). Such variations, even minuscule, can be exploited by sophisticated attackers to deduce sensitive information through side-channel timing attacks. This skill is vital for developers and security professionals who need to ensure their implementations of cryptographic primitives (encryption, decryption, signatures, key derivation) are robust against these subtle yet dangerous vulnerabilities. By identifying non-constant-time operations, the skill helps prevent the inadvertent leakage of secrets and strengthens the overall security posture of applications.

Best use case

Ideal for security auditing cryptographic implementations, validating the constant-time execution of sensitive operations, and proactively identifying potential side-channel timing vulnerabilities in code that handles secret data like private keys, tokens, or sensitive inputs.

Analyze cryptographic code to detect operations that leak secret data through execution timing variations.

The AI agent will provide an analysis of the submitted cryptographic code, highlighting specific lines or operations that are susceptible to timing variations and could leak secret data. It will identify potential non-constant-time operations and may offer recommendations for remediation or best practices to achieve constant-time execution.

Practical example

Example input

Can you analyze this Python code for any timing vulnerabilities, especially in how it handles the secret key?```python
def secure_compare(a, b):
    if len(a) != len(b):
        return False
    result = 0
    for i in range(len(a)):
        result |= a[i] ^ b[i]
    return result == 0

def decrypt_aes_cbc(ciphertext, key):
    # Simplified for example
    intermediate = process_blocks(ciphertext, key)
    return intermediate

# ... more crypto code ...
```

Example output

Upon analyzing your `secure_compare` function, I found that it appears to implement a constant-time comparison, which is good practice for mitigating timing attacks. However, the `decrypt_aes_cbc` function, particularly within `process_blocks` (which I cannot fully analyze without its definition), could introduce timing vulnerabilities if key-dependent operations or lookups are not performed in constant time. For instance, operations involving table lookups or variable-time modular arithmetic based on key values are common pitfalls. It's crucial to ensure that all operations related to the `key` within `decrypt_aes_cbc` execute in a fixed amount of time, regardless of the key's specific value. Consider using specific constant-time libraries or carefully auditing any division (`/`) or modulo (`%`) operations on secret-dependent data within your cryptographic primitives.

When to use this skill

  • This skill should be activated when the user is writing or reviewing cryptographic code (e.g., implementing signature, encryption, or key derivation functions). It is also highly relevant if the user is inquiring about timing attacks or if the code in question manipulates secret keys, tokens, or other sensitive data. Specific triggers include the presence of arithmetic operators like `/` (division) or `%` (modulo) when operating on secret-dependent values, which are common sources of timing variability.

When not to use this skill

  • Avoid using this skill when the code being analyzed does not involve cryptographic operations or does not handle secret, sensitive data. If the user's query is unrelated to code security, timing attacks, or the handling of secrets, this skill is not applicable.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/constant-time-analysis/SKILL.md --create-dirs "https://raw.githubusercontent.com/sickn33/antigravity-awesome-skills/main/plugins/antigravity-awesome-skills-claude/skills/constant-time-analysis/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/constant-time-analysis/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How constant-time-analysis Compares

Feature / Agentconstant-time-analysisStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Analyze cryptographic code to detect operations that leak secret data through execution timing variations.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Constant-Time Analysis

Analyze cryptographic code to detect operations that leak secret data through execution timing variations.

## When to Use
```text
User writing crypto code? ──yes──> Use this skill
         │
         no
         │
         v
User asking about timing attacks? ──yes──> Use this skill
         │
         no
         │
         v
Code handles secret keys/tokens? ──yes──> Use this skill
         │
         no
         │
         v
Skip this skill
```

**Concrete triggers:**

- User implements signature, encryption, or key derivation
- Code contains `/` or `%` operators on secret-derived values
- User mentions "constant-time", "timing attack", "side-channel", "KyberSlash"
- Reviewing functions named `sign`, `verify`, `encrypt`, `decrypt`, `derive_key`

## When NOT to Use

- Non-cryptographic code (business logic, UI, etc.)
- Public data processing where timing leaks don't matter
- Code that doesn't handle secrets, keys, or authentication tokens
- High-level API usage where timing is handled by the library

## Language Selection

Based on the file extension or language context, refer to the appropriate guide:

| Language   | File Extensions                   | Guide                                                    |
| ---------- | --------------------------------- | -------------------------------------------------------- |
| C, C++     | `.c`, `.h`, `.cpp`, `.cc`, `.hpp` | references/compiled.md         |
| Go         | `.go`                             | references/compiled.md         |
| Rust       | `.rs`                             | references/compiled.md         |
| Swift      | `.swift`                          | references/swift.md               |
| Java       | `.java`                           | references/vm-compiled.md   |
| Kotlin     | `.kt`, `.kts`                     | references/kotlin.md             |
| C#         | `.cs`                             | references/vm-compiled.md   |
| PHP        | `.php`                            | references/php.md                   |
| JavaScript | `.js`, `.mjs`, `.cjs`             | references/javascript.md     |
| TypeScript | `.ts`, `.tsx`                     | references/javascript.md     |
| Python     | `.py`                             | references/python.md             |
| Ruby       | `.rb`                             | references/ruby.md                 |

## Quick Start

```bash
# Analyze any supported file type
uv run {baseDir}/ct_analyzer/analyzer.py <source_file>

# Include conditional branch warnings
uv run {baseDir}/ct_analyzer/analyzer.py --warnings <source_file>

# Filter to specific functions
uv run {baseDir}/ct_analyzer/analyzer.py --func 'sign|verify' <source_file>

# JSON output for CI
uv run {baseDir}/ct_analyzer/analyzer.py --json <source_file>
```

### Native Compiled Languages Only (C, C++, Go, Rust)

```bash
# Cross-architecture testing (RECOMMENDED)
uv run {baseDir}/ct_analyzer/analyzer.py --arch x86_64 crypto.c
uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.c

# Multiple optimization levels
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.c
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O3 crypto.c
```

### VM-Compiled Languages (Java, Kotlin, C#)

```bash
# Analyze Java bytecode
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.java

# Analyze Kotlin bytecode (Android/JVM)
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.kt

# Analyze C# IL
uv run {baseDir}/ct_analyzer/analyzer.py CryptoUtils.cs
```

Note: Java, Kotlin, and C# compile to bytecode (JVM/CIL) that runs on a virtual machine with JIT compilation. The analyzer examines the bytecode directly, not the JIT-compiled native code. The `--arch` and `--opt-level` flags do not apply to these languages.

### Swift (iOS/macOS)

```bash
# Analyze Swift for native architecture
uv run {baseDir}/ct_analyzer/analyzer.py crypto.swift

# Analyze for specific architecture (iOS devices)
uv run {baseDir}/ct_analyzer/analyzer.py --arch arm64 crypto.swift

# Analyze with different optimization levels
uv run {baseDir}/ct_analyzer/analyzer.py --opt-level O0 crypto.swift
```

Note: Swift compiles to native code like C/C++/Go/Rust, so it uses assembly-level analysis and supports `--arch` and `--opt-level` flags.

### Prerequisites

| Language               | Requirements                                              |
| ---------------------- | --------------------------------------------------------- |
| C, C++, Go, Rust       | Compiler in PATH (`gcc`/`clang`, `go`, `rustc`)           |
| Swift                  | Xcode or Swift toolchain (`swiftc` in PATH)               |
| Java                   | JDK with `javac` and `javap` in PATH                      |
| Kotlin                 | Kotlin compiler (`kotlinc`) + JDK (`javap`) in PATH       |
| C#                     | .NET SDK + `ilspycmd` (`dotnet tool install -g ilspycmd`) |
| PHP                    | PHP with VLD extension or OPcache                         |
| JavaScript/TypeScript  | Node.js in PATH                                           |
| Python                 | Python 3.x in PATH                                        |
| Ruby                   | Ruby with `--dump=insns` support                          |

**macOS users**: Homebrew installs Java and .NET as "keg-only". You must add them to your PATH:

```bash
# For Java (add to ~/.zshrc)
export PATH="/opt/homebrew/opt/openjdk@21/bin:$PATH"

# For .NET tools (add to ~/.zshrc)
export PATH="$HOME/.dotnet/tools:$PATH"
```

See references/vm-compiled.md for detailed setup instructions and troubleshooting.

## Quick Reference

| Problem                | Detection                       | Fix                                          |
| ---------------------- | ------------------------------- | -------------------------------------------- |
| Division on secrets    | DIV, IDIV, SDIV, UDIV           | Barrett reduction or multiply-by-inverse     |
| Branch on secrets      | JE, JNE, BEQ, BNE               | Constant-time selection (cmov, bit masking)  |
| Secret comparison      | Early-exit memcmp               | Use `crypto/subtle` or constant-time compare |
| Weak RNG               | rand(), mt_rand, Math.random    | Use crypto-secure RNG                        |
| Table lookup by secret | Array subscript on secret index | Bit-sliced lookups                           |

## Interpreting Results

**PASSED** - No variable-time operations detected.

**FAILED** - Dangerous instructions found. Example:

```text
[ERROR] SDIV
  Function: decompose_vulnerable
  Reason: SDIV has early termination optimization; execution time depends on operand values
```

## Verifying Results (Avoiding False Positives)

**CRITICAL**: Not every flagged operation is a vulnerability. The tool has no data flow analysis - it flags ALL potentially dangerous operations regardless of whether they involve secrets.

For each flagged violation, ask: **Does this operation's input depend on secret data?**

1. **Identify the secret inputs** to the function (private keys, plaintext, signatures, tokens)

2. **Trace data flow** from the flagged instruction back to inputs

3. **Common false positive patterns**:

   ```c
   // FALSE POSITIVE: Division uses public constant, not secret
   int num_blocks = data_len / 16;  // data_len is length, not content

   // TRUE POSITIVE: Division involves secret-derived value
   int32_t q = secret_coef / GAMMA2;  // secret_coef from private key
   ```

4. **Document your analysis** for each flagged item

### Quick Triage Questions

| Question                                          | If Yes                | If No                 |
| ------------------------------------------------- | --------------------- | --------------------- |
| Is the operand a compile-time constant?           | Likely false positive | Continue              |
| Is the operand a public parameter (length, count)?| Likely false positive | Continue              |
| Is the operand derived from key/plaintext/secret? | **TRUE POSITIVE**     | Likely false positive |
| Can an attacker influence the operand value?      | **TRUE POSITIVE**     | Likely false positive |

## Limitations

1. **Static Analysis Only**: Analyzes assembly/bytecode, not runtime behavior. Cannot detect cache timing or microarchitectural side-channels.

2. **No Data Flow Analysis**: Flags all dangerous operations regardless of whether they process secrets. Manual review required.

3. **Compiler/Runtime Variations**: Different compilers, optimization levels, and runtime versions may produce different output.

## Real-World Impact

- **KyberSlash (2023)**: Division instructions in post-quantum ML-KEM implementations allowed key recovery
- **Lucky Thirteen (2013)**: Timing differences in CBC padding validation enabled plaintext recovery
- **RSA Timing Attacks**: Early implementations leaked private key bits through division timing

## References

- [Cryptocoding Guidelines](https://github.com/veorq/cryptocoding) - Defensive coding for crypto
- [KyberSlash](https://kyberslash.cr.yp.to/) - Division timing in post-quantum crypto
- [BearSSL Constant-Time](https://www.bearssl.org/constanttime.html) - Practical constant-time techniques

Related Skills

django-access-review

31392
from sickn33/antigravity-awesome-skills

django-access-review

Security AnalysisClaude

codebase-cleanup-deps-audit

31392
from sickn33/antigravity-awesome-skills

You are a dependency security expert specializing in vulnerability scanning, license compliance, and supply chain security. Analyze project dependencies for known vulnerabilities, licensing issues, outdated packages, and provide actionable remediation strategies.

Security AnalysisClaude

burpsuite-project-parser

31392
from sickn33/antigravity-awesome-skills

Searches and explores Burp Suite project files (.burp) from the command line. Use when searching response headers or bodies with regex patterns, extracting security audit findings, dumping proxy history or site map data, or analyzing HTTP traffic captured in a Burp project.

Security AnalysisClaude

market-sizing-analysis

31392
from sickn33/antigravity-awesome-skills

Comprehensive market sizing methodologies for calculating Total Addressable Market (TAM), Serviceable Available Market (SAM), and Serviceable Obtainable Market (SOM) for startup opportunities.

Business Intelligence & AnalyticsClaude

error-debugging-error-analysis

31392
from sickn33/antigravity-awesome-skills

You are an expert error analysis specialist with deep expertise in debugging distributed systems, analyzing production incidents, and implementing comprehensive observability solutions.

DevOps & InfrastructureClaude

azure-ai-vision-imageanalysis-py

31392
from sickn33/antigravity-awesome-skills

Azure AI Vision Image Analysis SDK for captions, tags, objects, OCR, people detection, and smart cropping. Use for computer vision and image understanding tasks.

Image AnalysisClaude

azure-ai-vision-imageanalysis-java

31392
from sickn33/antigravity-awesome-skills

Build image analysis applications with Azure AI Vision SDK for Java. Use when implementing image captioning, OCR text extraction, object detection, tagging, or smart cropping.

Image AnalysisClaude

nft-standards

31392
from sickn33/antigravity-awesome-skills

Master ERC-721 and ERC-1155 NFT standards, metadata best practices, and advanced NFT features.

Web3 & BlockchainClaude

nextjs-app-router-patterns

31392
from sickn33/antigravity-awesome-skills

Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development.

Web FrameworksClaude

new-rails-project

31392
from sickn33/antigravity-awesome-skills

Create a new Rails project

Code GenerationClaude

networkx

31392
from sickn33/antigravity-awesome-skills

NetworkX is a Python package for creating, manipulating, and analyzing complex networks and graphs.

Network AnalysisClaude

network-engineer

31392
from sickn33/antigravity-awesome-skills

Expert network engineer specializing in modern cloud networking, security architectures, and performance optimization.

Network EngineeringClaude