Skip to content

Latest commit

 

History

History
636 lines (508 loc) · 16.2 KB

File metadata and controls

636 lines (508 loc) · 16.2 KB

🚀 Real-World SDK Integration Guide

Complete Workflow: From Registration to Production Use

This guide shows exactly how a developer would use your CryptoShield SDK in a real application, from registration to production deployment.


📋 Table of Contents

  1. User Journey Overview
  2. Step 1: Register & Generate SDK
  3. Step 2: Download & Extract SDK
  4. Step 3: Integrate into Application
  5. Real-World Examples
  6. Production Deployment
  7. Monitoring & Telemetry

User Journey Overview

┌─────────────────┐
│ 1. Register     │ → User creates account on CryptoShield platform
└────────┬────────┘
         │
┌────────▼────────┐
│ 2. SDK Wizard   │ → Configure SDK (language, algorithms, compliance)
└────────┬────────┘
         │
┌────────▼────────┐
│ 3. Generate SDK │ → System generates custom SDK with unique ID
└────────┬────────┘
         │
┌────────▼────────┐
│ 4. Download ZIP │ → Download myapp-v2.0.0.zip
└────────┬────────┘
         │
┌────────▼────────┐
│ 5. Extract      │ → Unzip to project folder
└────────┬────────┘
         │
┌────────▼────────┐
│ 6. Install      │ → npm install / pip install
└────────┬────────┘
         │
┌────────▼────────┐
│ 7. Integrate    │ → Add encryption to application code
└────────┬────────┘
         │
┌────────▼────────┐
│ 8. Deploy       │ → Production deployment with monitoring
└─────────────────┘

Step 1: Register & Generate SDK

1.1 Create Account

1. Visit: https://cryptoshield.averox.com
2. Click "Sign Up" → Enter email, password
3. Verify email
4. Login to dashboard

1.2 Navigate to SDK Wizard

Dashboard → SDK Management → "Generate New SDK"

1.3 Configure SDK (Example: E-commerce Application)

Application Name: "ShopSecure"
Application Type: Web Application, Mobile App
Languages: JavaScript, Python
Security Level: Enterprise (AES-256-GCM + ChaCha20-Poly1305)
Data Types: Payment Data, PII, Health Records
Compliance: PCI-DSS, GDPR, HIPAA
Deployment: Production
Vault Integration: Enabled (Envelope Encryption)

1.4 Generate & Download

1. Click "Review & Generate"
2. System generates SDK with unique ID: sdk_a7f3e9d2c1b8456789
3. Download: ShopSecure-v2.0.0.zip (includes JavaScript & Python)

Step 2: Download & Extract SDK

Downloaded Package Structure

ShopSecure-v2.0.0.zip
├── javascript/
│   ├── src/
│   │   ├── index.ts          # Main SDK entry point
│   │   ├── metadata.ts       # SDK ID & configuration
│   │   └── crypto.ts         # Encryption implementation
│   ├── package.json
│   ├── tsconfig.json
│   ├── README.md
│   ├── test-sdk.ts           # Test suite
│   └── .sdk-metadata         # SDK ID file
├── python/
│   ├── averox_crypto/
│   │   ├── __init__.py
│   │   ├── metadata.py
│   │   └── crypto.py
│   ├── setup.py
│   ├── requirements.txt
│   ├── README.md
│   └── test_sdk.py
└── INTEGRATION-MANUAL.md     # This guide

Extract SDK

# Extract to your project directory
unzip ShopSecure-v2.0.0.zip
cd ShopSecure-v2.0.0

Step 3: Integrate into Application

Scenario: Node.js E-commerce Backend

3.1 Install SDK

cd ShopSecure-v2.0.0/javascript
npm install
npm run build

# Copy to your project
cp -r dist/ /path/to/your-ecommerce-app/lib/cryptoshield-sdk/

# Or install as local package
cd /path/to/your-ecommerce-app
npm install /path/to/ShopSecure-v2.0.0/javascript

3.2 Configure Environment Variables

# .env file in your application
VAULT_API_ENDPOINT=https://crypto.averox.com/api/vault/kek-shopsecure-prod
KEK_NAME=kek-shopsecure-prod
TENANT_ID=shopsecure-production
VAULT_ENABLED=true

3.3 Initialize SDK in Your Application

// config/crypto.js
import { AveroxCrypto, getSDKMetadata } from 'cryptoshield-sdk';

// Backend-managed envelope encryption (RECOMMENDED)
const cryptoConfig = {
  apiEndpoint: process.env.VAULT_API_ENDPOINT,
  kekName: process.env.KEK_NAME,
  context: process.env.TENANT_ID,
  enableEnvelopeEncryption: true
};

export const crypto = new AveroxCrypto(cryptoConfig);
export const sdkMetadata = getSDKMetadata();

console.log(`✅ CryptoShield SDK initialized`);
console.log(`   SDK ID: ${sdkMetadata.sdkId}`);
console.log(`   Tenant: ${sdkMetadata.metadata.tenant}`);
console.log(`   Vault: ${cryptoConfig.apiEndpoint}`);

Real-World Examples

Example 1: Encrypt Customer Payment Data

// routes/checkout.js
import { crypto } from '../config/crypto.js';
import { db } from '../config/database.js';

app.post('/api/checkout', async (req, res) => {
  try {
    const { userId, creditCard, cvv, billingAddress } = req.body;
    
    // 1. Prepare sensitive payment data
    const paymentData = {
      cardNumber: creditCard,
      cvv: cvv,
      billingAddress: billingAddress,
      timestamp: new Date().toISOString()
    };
    
    // 2. Encrypt with user ID as AAD (Additional Authenticated Data)
    const plaintext = JSON.stringify(paymentData);
    const aad = `user-${userId}`;
    
    const envelope = await crypto.encrypt(plaintext, aad);
    
    // 3. Store encrypted envelope in database
    await db.payments.create({
      userId: userId,
      encryptedPayment: envelope,  // Stores: {v, alg, kid, iv, tag, ct, aad, wrappedDEK}
      createdAt: new Date()
    });
    
    console.log(`✅ Payment data encrypted for user ${userId}`);
    res.json({ success: true, message: 'Payment processed securely' });
    
  } catch (error) {
    console.error('Encryption error:', error);
    res.status(500).json({ error: 'Payment processing failed' });
  }
});

Example 2: Decrypt Payment Data for Processing

// services/paymentProcessor.js
import { crypto } from '../config/crypto.js';
import { db } from '../config/database.js';

export async function processPayment(userId, orderId) {
  try {
    // 1. Retrieve encrypted payment data from database
    const payment = await db.payments.findOne({ 
      userId: userId,
      orderId: orderId 
    });
    
    if (!payment) {
      throw new Error('Payment not found');
    }
    
    // 2. Decrypt using same AAD
    const aad = `user-${userId}`;
    const decryptedBuffer = await crypto.decrypt(payment.encryptedPayment, aad);
    const paymentData = JSON.parse(decryptedBuffer.toString());
    
    // 3. Process payment with decrypted data
    const result = await chargeCard({
      cardNumber: paymentData.cardNumber,
      cvv: paymentData.cvv,
      amount: payment.amount
    });
    
    console.log(`✅ Payment processed for user ${userId}`);
    return result;
    
  } catch (error) {
    console.error('Decryption error:', error);
    throw new Error('Payment processing failed');
  }
}

Example 3: Encrypt User PII (Personal Identifiable Information)

// routes/users.js
import { crypto } from '../config/crypto.js';
import { db } from '../config/database.js';

app.post('/api/users/register', async (req, res) => {
  try {
    const { email, ssn, dateOfBirth, medicalRecordNumber } = req.body;
    
    // 1. Hash email for lookup (non-encrypted)
    const emailHash = hashEmail(email);
    
    // 2. Encrypt sensitive PII
    const piiData = {
      ssn: ssn,
      dateOfBirth: dateOfBirth,
      medicalRecordNumber: medicalRecordNumber
    };
    
    const plaintext = JSON.stringify(piiData);
    const aad = `user-pii-${emailHash}`;
    
    const envelope = await crypto.encrypt(plaintext, aad);
    
    // 3. Store user with encrypted PII
    const user = await db.users.create({
      emailHash: emailHash,
      encryptedPII: envelope,
      createdAt: new Date()
    });
    
    console.log(`✅ User registered with encrypted PII`);
    res.json({ success: true, userId: user.id });
    
  } catch (error) {
    console.error('User registration error:', error);
    res.status(500).json({ error: 'Registration failed' });
  }
});

Example 4: Encrypt Session Tokens

// middleware/auth.js
import { crypto } from '../config/crypto.js';
import jwt from 'jsonwebtoken';

export async function createSecureSession(userId, userData) {
  try {
    // 1. Create session data
    const sessionData = {
      userId: userId,
      email: userData.email,
      roles: userData.roles,
      createdAt: Date.now(),
      expiresAt: Date.now() + (24 * 60 * 60 * 1000) // 24 hours
    };
    
    // 2. Encrypt session data
    const plaintext = JSON.stringify(sessionData);
    const aad = `session-${userId}`;
    
    const envelope = await crypto.encrypt(plaintext, aad);
    
    // 3. Create JWT with encrypted session
    const token = jwt.sign(
      { 
        sessionId: generateSessionId(),
        encryptedSession: envelope 
      },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );
    
    return token;
    
  } catch (error) {
    console.error('Session creation error:', error);
    throw error;
  }
}

export async function validateSecureSession(token) {
  try {
    // 1. Verify JWT
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    
    // 2. Decrypt session data
    const aad = `session-${decoded.userId}`;
    const decryptedBuffer = await crypto.decrypt(decoded.encryptedSession, aad);
    const sessionData = JSON.parse(decryptedBuffer.toString());
    
    // 3. Validate expiration
    if (Date.now() > sessionData.expiresAt) {
      throw new Error('Session expired');
    }
    
    return sessionData;
    
  } catch (error) {
    console.error('Session validation error:', error);
    throw error;
  }
}

Example 5: Encrypt Database Backups

// scripts/backup.js
import { crypto } from '../config/crypto.js';
import { db } from '../config/database.js';
import fs from 'fs';

async function createEncryptedBackup() {
  try {
    // 1. Export database
    const data = await db.exportAll();
    const backupData = JSON.stringify(data);
    
    // 2. Encrypt backup
    const aad = `backup-${new Date().toISOString()}`;
    const envelope = await crypto.encrypt(backupData, aad);
    
    // 3. Save encrypted backup
    const backupFile = `backup-${Date.now()}.enc`;
    fs.writeFileSync(backupFile, JSON.stringify(envelope));
    
    console.log(`✅ Encrypted backup created: ${backupFile}`);
    console.log(`   AAD: ${aad}`);
    console.log(`   Size: ${(backupData.length / 1024 / 1024).toFixed(2)} MB`);
    
    return backupFile;
    
  } catch (error) {
    console.error('Backup error:', error);
    throw error;
  }
}

async function restoreEncryptedBackup(backupFile, aad) {
  try {
    // 1. Read encrypted backup
    const envelopeData = fs.readFileSync(backupFile, 'utf8');
    const envelope = JSON.parse(envelopeData);
    
    // 2. Decrypt backup
    const decryptedBuffer = await crypto.decrypt(envelope, aad);
    const backupData = JSON.parse(decryptedBuffer.toString());
    
    // 3. Restore database
    await db.importAll(backupData);
    
    console.log(`✅ Database restored from encrypted backup`);
    
  } catch (error) {
    console.error('Restore error:', error);
    throw error;
  }
}

Production Deployment

Step 1: Environment Configuration

# Production .env
NODE_ENV=production
VAULT_API_ENDPOINT=https://vault.yourcompany.com/api/vault/kek-prod-abc123
KEK_NAME=kek-prod-abc123
TENANT_ID=yourcompany-production
VAULT_ENABLED=true
VAULT_TIMEOUT=5000
VAULT_RETRIES=3

Step 2: Docker Deployment

# Dockerfile
FROM node:18-alpine

WORKDIR /app

# Copy SDK
COPY ShopSecure-v2.0.0/javascript/dist ./lib/cryptoshield-sdk

# Copy application
COPY package*.json ./
RUN npm install --production

COPY . .

# Environment variables will be injected at runtime
ENV NODE_ENV=production

EXPOSE 3000
CMD ["node", "server.js"]

Step 3: Kubernetes Deployment

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shopsecure-api
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: api
        image: shopsecure/api:latest
        env:
        - name: VAULT_API_ENDPOINT
          valueFrom:
            secretKeyRef:
              name: crypto-config
              key: vault-endpoint
        - name: KEK_NAME
          valueFrom:
            secretKeyRef:
              name: crypto-config
              key: kek-name
        - name: TENANT_ID
          value: "shopsecure-production"

Step 4: Error Handling & Logging

// middleware/errorHandler.js
import { sdkMetadata } from '../config/crypto.js';

export function cryptoErrorHandler(error, req, res, next) {
  // Log error with SDK context
  console.error({
    sdkId: sdkMetadata.sdkId,
    tenant: sdkMetadata.metadata.tenant,
    operation: req.path,
    error: error.message,
    timestamp: new Date().toISOString()
  });
  
  // Handle specific encryption errors
  if (error.message.includes('Authentication')) {
    return res.status(400).json({ 
      error: 'Data integrity check failed',
      code: 'CRYPTO_AUTH_FAILED'
    });
  }
  
  if (error.message.includes('Backend')) {
    return res.status(503).json({ 
      error: 'Encryption service unavailable',
      code: 'CRYPTO_SERVICE_UNAVAILABLE'
    });
  }
  
  // Generic error
  res.status(500).json({ 
    error: 'Internal server error',
    code: 'INTERNAL_ERROR'
  });
}

Monitoring & Telemetry

View SDK Usage in Dashboard

1. Login to CryptoShield Dashboard
2. Navigate to: SDK Management
3. Click on: "ShopSecure" SDK
4. Go to: Telemetry Tab

Real-Time Metrics Displayed

Operations:
  - Total Encryptions: 1,234,567
  - Total Decryptions: 987,654
  - Success Rate: 99.98%
  - Average Duration: 12ms

Errors:
  - Authentication Failures: 15 (0.001%)
  - Backend Timeouts: 8 (0.0006%)
  - Invalid AAD: 3 (0.0002%)

Performance:
  - P50 Latency: 8ms
  - P95 Latency: 25ms
  - P99 Latency: 45ms

Platform:
  - Node.js: 95%
  - Python: 5%
  - SDK Version: 2.0.0

Custom Monitoring Integration

// monitoring/telemetry.js
import { sdkMetadata } from '../config/crypto.js';

export function logCryptoOperation(operation, duration, success, error = null) {
  const telemetryData = {
    sdkId: sdkMetadata.sdkId,
    tenant: sdkMetadata.metadata.tenant,
    operation: operation,
    duration: duration,
    success: success,
    error: error,
    timestamp: new Date().toISOString()
  };
  
  // Send to your monitoring system
  sendToDatadog(telemetryData);
  sendToCloudWatch(telemetryData);
  
  // Also sent automatically to CryptoShield dashboard
}

Summary

What the Developer Gets

Custom SDK - Generated specifically for their application ✅ Unique SDK ID - For tracking and monitoring ✅ Zero Key Management - Backend handles all encryption keys via Vault ✅ Production Ready - Enterprise-grade security out of the box ✅ Real-Time Monitoring - View usage metrics in dashboard ✅ Compliance Built-in - PCI-DSS, GDPR, HIPAA compliant ✅ Multi-Language - JavaScript, Python, Go, PHP, etc. ✅ Test Suite - Comprehensive tests included

Integration Time

  • Setup: 15 minutes
  • First Integration: 30 minutes
  • Production Deployment: 1-2 hours
  • Total: ~2-3 hours from download to production

Support

  • 📖 Documentation: Included in SDK package
  • 🔍 Telemetry: Real-time monitoring in dashboard
  • 💬 Support: support@averox.com
  • 🐛 Issues: GitHub issues or dashboard support ticket

Ready to secure your application? Download your custom SDK today!