Skip to content

Code Examples

Practical examples and tutorials for integrating Sharokey into your applications. All examples demonstrate Zero Knowledge encryption best practices.

🚀 Quick Start Examples

Simple Secret Creation

bash
# Basic secret
sharokey create "My database password" --hours 24 --views 1

# With description
sharokey create "MySQL root password" \
  --hours 2 --views 1 \
  --description "Production DB credentials"
javascript
// Include script in HTML first: <script src="sharokey.js"></script>

// Configure once
Sharokey.config({ token: 'your-api-token' });

// Basic secret
const secret = await Sharokey.create('My database password', 24, 1);
console.log(`Share this URL: ${secret.share_url}`);

// With description
const secret2 = await Sharokey.create(
  'MySQL root password', 
  2, 1, 
  { description: 'Production DB credentials' }
);
python
import asyncio
import sharokey

async def main():
    client = sharokey.SharokeyClient(token='your-api-token')
    
    # Basic secret
    secret = await client.create('My database password', 24, 1)
    print(f'Share this URL: {secret.share_url}')
    
    # With description  
    secret2 = await client.create(
        'MySQL root password',
        hours=2,
        views=1,
        description='Production DB credentials'
    )

asyncio.run(main())

Password Protected Secrets

bash
sharokey create "Super secret data" \
  --hours 1 --views 1 \
  --password "my-protection-password" \
  --description "Extra protected secret"
javascript
const secret = await Sharokey.create(
  'Super secret data',
  1, 1,
  {
    password: 'my-protection-password',
    description: 'Extra protected secret'
  }
);
python
secret = await client.create(
    'Super secret data',
    hours=1,
    views=1,
    password='my-protection-password',
    description='Extra protected secret'
)

📎 File Attachment Examples

Single File Upload

bash
sharokey create "Contract for review" \
  --hours 48 --views 5 \
  --attach contract.pdf \
  --description "Legal contract - needs approval"
javascript
// From file input
const fileInput = document.getElementById('file');
const file = fileInput.files[0];

const secret = await Sharokey.create(
  'Contract for review',
  48, 5,
  {
    attachments: [file],
    description: 'Legal contract - needs approval'
  }
);

// From Node.js
import fs from 'fs';

const fileBuffer = fs.readFileSync('contract.pdf');
const secret = await client.createSecret('Contract for review', {
  expirationHours: 48,
  maximumViews: 5,
  attachments: [{
    name: 'contract.pdf',
    data: fileBuffer
  }],
  description: 'Legal contract - needs approval'
});
python
secret = await client.create(
    'Contract for review',
    hours=48,
    views=5,
    attachments=['contract.pdf'],
    description='Legal contract - needs approval'
)

Multiple Files

bash
sharokey create "Project documentation" \
  --hours 72 --views 10 \
  --attach README.md \
  --attach specs.pdf \
  --attach design.png \
  --description "Complete project package"
javascript
// Multiple files from input
const files = Array.from(fileInput.files);

const secret = await Sharokey.create(
  'Project documentation',
  72, 10,
  {
    attachments: files,
    description: 'Complete project package'
  }
);
python
secret = await client.create(
    'Project documentation',
    hours=72,
    views=10,
    attachments=[
        'README.md',
        'specs.pdf', 
        'design.png'
    ],
    description='Complete project package'
)

📱 OTP Protection Examples

Email OTP

bash
sharokey create "Sensitive server credentials" \
  --hours 1 --views 1 \
  --otp-email "[email protected]" \
  --description "Production server access"
javascript
const secret = await Sharokey.create(
  'Sensitive server credentials',
  1, 1,
  {
    otp_email: '[email protected]',
    description: 'Production server access'
  }
);
python
secret = await client.create(
    'Sensitive server credentials',
    hours=1,
    views=1,
    otp_email='[email protected]',
    description='Production server access'
)

SMS OTP

bash
sharokey create "Emergency access code" \
  --hours 2 --views 1 \
  --otp-phone "+1234567890" \
  --description "Emergency system access"
javascript
const secret = await Sharokey.create(
  'Emergency access code',
  2, 1,
  {
    otp_phone: '+1234567890',
    description: 'Emergency system access'
  }
);
python
secret = await client.create(
    'Emergency access code',
    hours=2,
    views=1,
    otp_phone='+1234567890',
    description='Emergency system access'
)

🛡️ Advanced Security Examples

CAPTCHA Protection

bash
sharokey create "Protected content" \
  --hours 2 --views 1 \
  --captcha \
  --description "CAPTCHA required to access"
javascript
const secret = await Sharokey.create(
  'Protected content',
  2, 1,
  {
    captcha: true,
    description: 'CAPTCHA required to access'
  }
);
python
secret = await client.create(
    'Protected content',
    hours=2,
    views=1,
    captcha=True,
    description='CAPTCHA required to access'
)

IP Whitelist Restrictions

bash
# Single IP and CIDR block
sharokey create "Internal documentation" \
  --hours 24 --views 5 \
  --ip-whitelist "192.168.1.100,10.0.0.0/24" \
  --description "Only accessible from internal network"

# Multiple specific IPs
sharokey create "Server credentials" \
  --hours 1 --views 1 \
  --ip-whitelist "203.0.113.5,198.51.100.10,192.0.2.15" \
  --description "Admin server access"
javascript
const secret = await Sharokey.create(
  'Internal documentation',
  24, 5,
  {
    ip_whitelist: '192.168.1.100,10.0.0.0/24',
    description: 'Only accessible from internal network'
  }
);
python
secret = await client.create(
    'Internal documentation',
    hours=24,
    views=5,
    ip_whitelist='192.168.1.100,10.0.0.0/24',
    description='Only accessible from internal network'
)

Geolocation Restrictions

bash
# EU countries only
sharokey create "GDPR sensitive data" \
  --hours 6 --views 3 \
  --geolocation "FR,DE,BE,NL,IT,ES" \
  --description "European Union access only"

# North America
sharokey create "Regional configuration" \
  --hours 12 --views 2 \
  --geolocation "US,CA,MX" \
  --description "North American servers config"
javascript
const secret = await Sharokey.create(
  'GDPR sensitive data',
  6, 3,
  {
    geolocation: 'FR,DE,BE,NL,IT,ES',
    description: 'European Union access only'
  }
);
python
secret = await client.create(
    'GDPR sensitive data',
    hours=6,
    views=3,
    geolocation='FR,DE,BE,NL,IT,ES',
    description='European Union access only'
)

Combined Security (Maximum Protection)

bash
sharokey create "Top secret information" \
  --hours 1 --views 1 \
  --captcha \
  --ip-whitelist "192.168.1.0/24" \
  --geolocation "FR,US" \
  --otp-email "[email protected]" \
  --password "extra-secure-123" \
  --message "Handle with extreme care - contains sensitive data" \
  --description "Maximum security secret"
javascript
const secret = await Sharokey.create(
  'Top secret information',
  1, 1,
  {
    captcha: true,
    ip_whitelist: '192.168.1.0/24',
    geolocation: 'FR,US',
    otp_email: '[email protected]',
    password: 'extra-secure-123',
    message: 'Handle with extreme care - contains sensitive data',
    description: 'Maximum security secret'
  }
);
python
secret = await client.create(
    'Top secret information',
    hours=1,
    views=1,
    captcha=True,
    ip_whitelist='192.168.1.0/24',
    geolocation='FR,US',
    otp_email='[email protected]',
    password='extra-secure-123',
    message='Handle with extreme care - contains sensitive data',
    description='Maximum security secret'
)

Custom Messages

bash
sharokey create "Monthly report data" \
  --hours 48 --views 10 \
  --message "Please review by Friday and provide feedback via email" \
  --description "Q3 Financial Report"
javascript
const secret = await Sharokey.create(
  'Monthly report data',
  48, 10,
  {
    message: 'Please review by Friday and provide feedback via email',
    description: 'Q3 Financial Report'
  }
);
python
secret = await client.create(
    'Monthly report data',
    hours=48,
    views=10,
    message='Please review by Friday and provide feedback via email',
    description='Q3 Financial Report'
)

🔍 Secret Management Examples

List and Filter Secrets

bash
# List all secrets
sharokey list

# Filter by status
sharokey list --status active

# Limit results
sharokey list --limit 10

# Search by description
sharokey list --search "database"
javascript
// List all secrets
const secrets = await Sharokey.list();
console.log(`Total: ${secrets.count} secrets`);

// With filters (JS Complete only)
const activeSecrets = await client.getSecrets({
  status: 'active',
  limit: 10,
  search: 'database'
});
python
# List all secrets
secrets = await client.list()
print(f'Total: {secrets.count} secrets')

# With filters
active_secrets = await client.list(
    status='active',
    limit=10,
    search='database'
)

# Print results
for secret in active_secrets.data:
    remaining = secret.maximum_views - secret.current_views
    print(f'{secret.slug}: {secret.description} ({remaining} views left)')

Get Secret Details

bash
sharokey get ABC123XYZ
javascript
const secret = await Sharokey.get('ABC123XYZ');
console.log(`Description: ${secret.description}`);
console.log(`Views: ${secret.current_views}/${secret.maximum_views}`);
console.log(`Expires: ${secret.expiration}`);
python
secret = await client.get('ABC123XYZ')
print(f'Description: {secret.description}')
print(f'Views: {secret.current_views}/{secret.maximum_views}')
print(f'Expires: {secret.expiration}')
print(f'Has attachments: {secret.has_attachments}')

Delete Secrets

bash
sharokey delete ABC123XYZ
javascript
const success = await Sharokey.delete('ABC123XYZ');
if (success) {
  console.log('Secret deleted successfully');
}
python
success = await client.delete('ABC123XYZ')
if success:
    print('Secret deleted successfully')

📊 Statistics Examples

bash
sharokey stats
javascript
const stats = await Sharokey.stats();
console.log(`Total secrets: ${stats.total_secrets}`);
console.log(`Active secrets: ${stats.active_secrets}`);
console.log(`Total views: ${stats.total_views}`);
python
stats = await client.stats()
print(f'Total secrets: {stats.total_secrets}')
print(f'Active secrets: {stats.active_secrets}')
print(f'Expired secrets: {stats.expired_secrets}')
print(f'Total views: {stats.total_views}')

🛠️ Practical Integration Examples

Environment-based Configuration

bash
# Set environment variable
export SHAROKEY_TOKEN="your-api-token"
export SHAROKEY_API_URL="https://api.sharokey.com"

# CLI will automatically use environment variables
sharokey create "My secret"
javascript
// Use environment variables
Sharokey.config({
  token: process.env.SHAROKEY_TOKEN,
  apiUrl: process.env.SHAROKEY_API_URL || 'https://api.sharokey.com'
});
python
import os

client = sharokey.SharokeyClient(
    token=os.getenv('SHAROKEY_TOKEN'),
    api_url=os.getenv('SHAROKEY_API_URL', 'https://api.sharokey.com')
)

Error Handling

javascript
try {
  const secret = await Sharokey.create('', -1, 0); // Invalid parameters
} catch (error) {
  if (error.name === 'ValidationError') {
    console.error('Validation error:', error.message);
  } else if (error.name === 'AuthenticationError') {
    console.error('Authentication failed:', error.message);
  } else if (error.name === 'NetworkError') {
    console.error('Network error:', error.message);
  }
}
python
try:
    secret = await client.create('', -1, 0)  # Invalid parameters
except sharokey.ValidationError as e:
    print(f'Validation error: {e}')
except sharokey.AuthenticationError as e:
    print(f'Authentication failed: {e}')
except sharokey.NetworkError as e:
    print(f'Network error: {e}')
except sharokey.SharokeyError as e:
    print(f'General error: {e}')

🔗 Next Steps

💡 Best Practices

  1. Always set appropriate expiration times - Don't use overly long durations
  2. Use view limits effectively - Limit to actual expected usage
  3. Add descriptive messages - Help recipients understand the content
  4. Validate file sizes - Stay within the 10MB attachment limit
  5. Handle errors gracefully - Implement proper error handling
  6. Use OTP for sensitive data - Add extra protection when needed
  7. Clean up expired secrets - Regular maintenance keeps things tidy

💡 Pro Tip

Use environment variables for API tokens and never commit them to version control. This keeps your credentials secure across different deployment environments.

Released under the MIT License.