Scaling Codes Logo
Scaling Codes

Cryptography MCP

Provide AI models with encryption, hashing, and cryptographic operations

SecurityExpertMCP Protocol

Overview

The Cryptography MCP provides AI models with secure access to cryptographic operations including encryption, decryption, hashing, digital signatures, and key management while maintaining strict security controls and preventing misuse.

This protocol is essential for AI models that need to work with sensitive data, implement security features, or perform cryptographic operations in a controlled environment.

Implementation Guide

1. Cryptography MCP Server

import { Server } from '@modelcontextprotocol/sdk/server'
import { CryptographyTool } from './tools/CryptographyTool'
import crypto from 'crypto'

const server = new Server({
  name: 'cryptography-mcp',
  version: '1.0.0'
})

// Register cryptography tool
server.tool(new CryptographyTool({
  allowedAlgorithms: ['AES-256-GCM', 'SHA-256', 'RSA-OAEP'],
  blockedAlgorithms: ['MD5', 'DES', 'RC4'],
  keyManagement: {
    maxKeySize: 4096,
    keyRotation: true,
    secureStorage: true
  }
}))

server.listen({
  port: 3000,
  host: 'localhost'
})

2. Cryptography Tool Implementation

import { Tool } from '@modelcontextprotocol/sdk/server'
import crypto from 'crypto'

interface CryptographyConfig {
  allowedAlgorithms: string[]
  blockedAlgorithms: string[]
  keyManagement: {
    maxKeySize: number
    keyRotation: boolean
    secureStorage: boolean
  }
}

export class CryptographyTool extends Tool {
  private config: CryptographyConfig
  
  constructor(config: CryptographyConfig) {
    super({
      name: 'cryptography',
      description: 'Perform cryptographic operations securely',
      inputSchema: {
        type: 'object',
        properties: {
          operation: { type: 'string', enum: ['encrypt', 'decrypt', 'hash', 'sign', 'verify'] },
          algorithm: { type: 'string' },
          data: { type: 'string' },
          key: { type: 'string' },
          iv: { type: 'string' }
        },
        required: ['operation', 'algorithm', 'data']
      }
    })
    this.config = config
  }

  async execute(input: any) {
    // Validate algorithm
    if (!this.isAlgorithmAllowed(input.algorithm)) {
      throw new Error(`Algorithm ${input.algorithm} not allowed`)
    }

    // Execute operation
    switch (input.operation) {
      case 'encrypt':
        return await this.encrypt(input.data, input.algorithm, input.key, input.iv)
      case 'decrypt':
        return await this.decrypt(input.data, input.algorithm, input.key, input.iv)
      case 'hash':
        return await this.hash(input.data, input.algorithm)
      case 'sign':
        return await this.sign(input.data, input.algorithm, input.key)
      case 'verify':
        return await this.verify(input.data, input.algorithm, input.key, input.signature)
      default:
        throw new Error(`Unknown operation: ${input.operation}`)
    }
  }

  private isAlgorithmAllowed(algorithm: string): boolean {
    if (this.config.blockedAlgorithms.includes(algorithm)) {
      return false
    }
    return this.config.allowedAlgorithms.includes(algorithm)
  }

  private async encrypt(data: string, algorithm: string, key: string, iv?: string): Promise<any> {
    try {
      if (algorithm.startsWith('AES')) {
        const cipher = crypto.createCipher(algorithm, key)
        if (iv) cipher.setAutoPadding(false)
        
        let encrypted = cipher.update(data, 'utf8', 'hex')
        encrypted += cipher.final('hex')
        
        return {
          encrypted,
          iv: iv || cipher.getIV(),
          algorithm,
          timestamp: new Date().toISOString()
        }
      } else if (algorithm.startsWith('RSA')) {
        const publicKey = Buffer.from(key, 'base64')
        const encrypted = crypto.publicEncrypt(
          { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
          Buffer.from(data, 'utf8')
        )
        
        return {
          encrypted: encrypted.toString('base64'),
          algorithm,
          timestamp: new Date().toISOString()
        }
      }
      
      throw new Error(`Unsupported encryption algorithm: ${algorithm}`)
    } catch (error) {
      throw new Error(`Encryption failed: ${error.message}`)
    }
  }

  private async decrypt(data: string, algorithm: string, key: string, iv?: string): Promise<any> {
    try {
      if (algorithm.startsWith('AES')) {
        const decipher = crypto.createDecipher(algorithm, key)
        if (iv) decipher.setAutoPadding(false)
        
        let decrypted = decipher.update(data, 'hex', 'utf8')
        decrypted += decipher.final('utf8')
        
        return {
          decrypted,
          algorithm,
          timestamp: new Date().toISOString()
        }
      } else if (algorithm.startsWith('RSA')) {
        const privateKey = Buffer.from(key, 'base64')
        const decrypted = crypto.privateDecrypt(
          { key: privateKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING },
          Buffer.from(data, 'base64')
        )
        
        return {
          decrypted: decrypted.toString('utf8'),
          algorithm,
          timestamp: new Date().toISOString()
        }
      }
      
      throw new Error(`Unsupported decryption algorithm: ${algorithm}`)
    } catch (error) {
      throw new Error(`Decryption failed: ${error.message}`)
    }
  }

  private async hash(data: string, algorithm: string): Promise<any> {
    try {
      const hash = crypto.createHash(algorithm)
      hash.update(data, 'utf8')
      
      return {
        hash: hash.digest('hex'),
        algorithm,
        timestamp: new Date().toISOString()
      }
    } catch (error) {
      throw new Error(`Hashing failed: ${error.message}`)
    }
  }

  private async sign(data: string, algorithm: string, privateKey: string): Promise<any> {
    try {
      const key = Buffer.from(privateKey, 'base64')
      const sign = crypto.createSign(algorithm)
      sign.update(data, 'utf8')
      
      const signature = sign.sign(key, 'base64')
      
      return {
        signature,
        algorithm,
        timestamp: new Date().toISOString()
      }
    } catch (error) {
      throw new Error(`Signing failed: ${error.message}`)
    }
  }

  private async verify(data: string, algorithm: string, publicKey: string, signature: string): Promise<any> {
    try {
      const key = Buffer.from(publicKey, 'base64')
      const verify = crypto.createVerify(algorithm)
      verify.update(data, 'utf8')
      
      const isValid = verify.verify(key, signature, 'base64')
      
      return {
        isValid,
        algorithm,
        timestamp: new Date().toISOString()
      }
    } catch (error) {
      throw new Error(`Verification failed: ${error.message}`)
    }
  }
}

3. Client Integration

import { Client } from '@modelcontextprotocol/sdk/client'

const client = new Client({
  serverUrl: 'ws://localhost:3000'
})

// Example: Encrypt sensitive data
const encrypted = await client.tools.cryptography.execute({
  operation: 'encrypt',
  algorithm: 'AES-256-GCM',
  data: 'sensitive information',
  key: 'your-secret-key'
})

console.log('Encrypted data:', encrypted.encrypted)

// Example: Hash password
const hashedPassword = await client.tools.cryptography.execute({
  operation: 'hash',
  algorithm: 'SHA-256',
  data: 'user-password-123'
})

console.log('Hashed password:', hashedPassword.hash)

// Example: Sign document
const signature = await client.tools.cryptography.execute({
  operation: 'sign',
  algorithm: 'RSA-SHA256',
  data: 'document content to sign',
  key: 'base64-encoded-private-key'
})

console.log('Digital signature:', signature.signature)

// Example: Verify signature
const verification = await client.tools.cryptography.execute({
  operation: 'verify',
  algorithm: 'RSA-SHA256',
  data: 'document content to verify',
  key: 'base64-encoded-public-key',
  signature: 'base64-encoded-signature'
})

console.log('Signature valid:', verification.isValid)

Configuration Example

# cryptography-mcp-config.yaml
server:
  name: cryptography-mcp
  version: 1.0.0
  port: 3000
  host: localhost

cryptography:
  allowed_algorithms:
    encryption:
      - AES-256-GCM
      - AES-256-CBC
      - RSA-OAEP
      - ChaCha20-Poly1305
    
    hashing:
      - SHA-256
      - SHA-384
      - SHA-512
      - Blake2b
    
    signing:
      - RSA-SHA256
      - RSA-SHA384
      - RSA-SHA512
      - Ed25519
  
  blocked_algorithms:
    - MD5
    - SHA-1
    - DES
    - RC4
    - 3DES
  
  key_management:
    max_key_size: 4096
    key_rotation: true
    rotation_interval: 90d
    secure_storage: true
    key_encryption: true
    
    storage:
      type: "hardware_security_module"
      provider: "aws_kms"
      region: "us-east-1"
      key_alias: "mcp-crypto-key"
  
  security:
    entropy_source: "/dev/urandom"
    secure_random: true
    key_derivation: "PBKDF2"
    salt_length: 32
    iterations: 100000
    
    access_control:
      require_authentication: true
      role_based_access: true
      audit_logging: true
      rate_limiting: true
  
  monitoring:
    metrics:
      enabled: true
      track_operations: true
      track_performance: true
      track_errors: true
    
    alerts:
      failed_operations: true
      performance_degradation: true
      security_violations: true

Common Use Cases

Data Protection

AI models can encrypt sensitive data, generate secure hashes for passwords, and implement data protection measures while maintaining security standards.

Digital Signatures

AI models can sign documents, verify signatures, and implement non-repudiation features for secure document workflows and authentication.

Secure Communication

AI models can implement end-to-end encryption, secure key exchange, and cryptographic protocols for secure communication channels.