Wallet Security

Comprehensive guide to securing your digital wallet, including best practices for private key management, transaction security, and protection against common threats.

Overview

Wallet security is critical for protecting your digital assets. This guide covers all aspects of wallet security from basic setup to advanced protection mechanisms against theft, fraud, and technical vulnerabilities.

Wallet Types and Security Levels

Hot Wallets (Online)

Security Level: Medium Use Case: Daily trading and transactions

Characteristics:

  • Connected to the internet
  • Easy access and convenience
  • Higher risk of online attacks
  • Suitable for small amounts

Security Measures:

  • Strong passwords and 2FA
  • Regular software updates
  • Antivirus protection
  • Secure network connections

Warm Wallets (Semi-Offline)

Security Level: High Use Case: Regular trading with enhanced security

Characteristics:

  • Limited internet connectivity
  • Balance between security and convenience
  • Reduced attack surface
  • Suitable for medium amounts

Security Measures:

  • Air-gapped transaction signing
  • Multi-signature requirements
  • Hardware security modules
  • Regular security audits

Cold Wallets (Offline)

Security Level: Very High Use Case: Long-term storage and large amounts

Characteristics:

  • Never connected to the internet
  • Maximum security
  • Reduced convenience
  • Suitable for large amounts

Security Measures:

  • Physical security
  • Secure key generation
  • Offline transaction signing
  • Backup and recovery procedures

Private Key Management

Key Generation

Secure Random Generation

import secrets
import hashlib
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

class SecureKeyGenerator:
    def __init__(self):
        self.entropy_source = secrets.SystemRandom()
    
    def generate_private_key(self, key_length=256):
        # Generate cryptographically secure random bytes
        private_key = self.entropy_source.getrandbits(key_length)
        return private_key
    
    def generate_from_mnemonic(self, mnemonic_phrase, passphrase=""):
        # Generate key from mnemonic using PBKDF2
        salt = hashlib.sha256(mnemonic_phrase.encode()).digest()
        
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=2048,
        )
        
        key = kdf.derive((mnemonic_phrase + passphrase).encode())
        return key

Hardware Security Module (HSM)

class HSMKeyManager:
    def __init__(self, hsm_device):
        self.hsm = hsm_device
    
    def generate_key_pair(self, key_id):
        # Generate key pair in HSM
        private_key = self.hsm.generate_private_key(key_id)
        public_key = self.hsm.get_public_key(key_id)
        return private_key, public_key
    
    def sign_transaction(self, key_id, transaction_data):
        # Sign transaction using HSM
        signature = self.hsm.sign(key_id, transaction_data)
        return signature
    
    def verify_signature(self, public_key, signature, data):
        # Verify signature using HSM
        return self.hsm.verify(public_key, signature, data)

Key Storage

Encrypted Key Storage

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
import os

class EncryptedKeyStorage:
    def __init__(self, master_password):
        self.master_password = master_password.encode()
        self.salt = os.urandom(16)
        self.key = self._derive_key()
    
    def _derive_key(self):
        kdf = PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=self.salt,
            iterations=100000,
        )
        key = base64.urlsafe_b64encode(kdf.derive(self.master_password))
        return key
    
    def encrypt_private_key(self, private_key):
        f = Fernet(self.key)
        encrypted_key = f.encrypt(str(private_key).encode())
        return encrypted_key
    
    def decrypt_private_key(self, encrypted_key):
        f = Fernet(self.key)
        decrypted_key = f.decrypt(encrypted_key)
        return decrypted_key.decode()
    
    def store_key(self, key_id, private_key):
        encrypted_key = self.encrypt_private_key(private_key)
        # Store encrypted key securely
        self._persist_key(key_id, encrypted_key)
    
    def retrieve_key(self, key_id):
        encrypted_key = self._load_key(key_id)
        return self.decrypt_private_key(encrypted_key)

Multi-Signature Wallets

class MultiSigWallet:
    def __init__(self, required_signatures, total_signatures):
        self.required_signatures = required_signatures
        self.total_signatures = total_signatures
        self.public_keys = []
        self.private_keys = []
    
    def add_key_pair(self, public_key, private_key):
        self.public_keys.append(public_key)
        self.private_keys.append(private_key)
    
    def create_transaction(self, transaction_data):
        # Create transaction requiring multiple signatures
        transaction = {
            'data': transaction_data,
            'required_signatures': self.required_signatures,
            'public_keys': self.public_keys,
            'signatures': []
        }
        return transaction
    
    def sign_transaction(self, transaction, key_index):
        if key_index >= len(self.private_keys):
            raise ValueError("Invalid key index")
        
        # Sign transaction with specific private key
        signature = self._sign_with_key(transaction, self.private_keys[key_index])
        transaction['signatures'].append({
            'signature': signature,
            'public_key': self.public_keys[key_index]
        })
        
        return transaction
    
    def verify_transaction(self, transaction):
        if len(transaction['signatures']) < self.required_signatures:
            return False
        
        # Verify all signatures
        for sig_data in transaction['signatures']:
            if not self._verify_signature(transaction, sig_data):
                return False
        
        return True

Transaction Security

Transaction Validation

Input Validation

class TransactionValidator:
    def __init__(self):
        self.max_amount = 1000000  # Maximum transaction amount
        self.min_amount = 0.0001   # Minimum transaction amount
    
    def validate_transaction(self, transaction):
        errors = []
        
        # Validate amount
        if not self._validate_amount(transaction['amount']):
            errors.append("Invalid transaction amount")
        
        # Validate recipient address
        if not self._validate_address(transaction['recipient']):
            errors.append("Invalid recipient address")
        
        # Validate transaction data
        if not self._validate_data(transaction['data']):
            errors.append("Invalid transaction data")
        
        # Check for suspicious patterns
        if self._detect_suspicious_pattern(transaction):
            errors.append("Suspicious transaction pattern detected")
        
        return len(errors) == 0, errors
    
    def _validate_amount(self, amount):
        return self.min_amount <= amount <= self.max_amount
    
    def _validate_address(self, address):
        # Validate cryptocurrency address format
        return len(address) >= 26 and len(address) <= 62
    
    def _validate_data(self, data):
        # Validate transaction data
        return isinstance(data, dict) and 'type' in data
    
    def _detect_suspicious_pattern(self, transaction):
        # Detect suspicious transaction patterns
        suspicious_patterns = [
            'very_large_amount',
            'unusual_recipient',
            'rapid_succession',
            'round_number_amount'
        ]
        
        for pattern in suspicious_patterns:
            if self._check_pattern(transaction, pattern):
                return True
        
        return False

Double-Spend Prevention

class DoubleSpendPrevention:
    def __init__(self):
        self.spent_outputs = set()
        self.pending_transactions = {}
    
    def check_double_spend(self, transaction):
        # Check if any input has already been spent
        for input_tx in transaction['inputs']:
            if input_tx['output_hash'] in self.spent_outputs:
                return False, "Double spend detected"
        
        # Check if any input is in pending transactions
        for input_tx in transaction['inputs']:
            if input_tx['output_hash'] in self.pending_transactions:
                return False, "Input already in pending transaction"
        
        return True, "No double spend detected"
    
    def mark_outputs_spent(self, transaction):
        # Mark outputs as spent
        for input_tx in transaction['inputs']:
            self.spent_outputs.add(input_tx['output_hash'])
    
    def add_pending_transaction(self, transaction):
        # Add transaction to pending list
        tx_hash = self._calculate_transaction_hash(transaction)
        self.pending_transactions[tx_hash] = transaction
        
        # Mark inputs as pending
        for input_tx in transaction['inputs']:
            self.pending_transactions[input_tx['output_hash']] = transaction

Transaction Signing

Secure Signing Process

import hashlib
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding

class SecureTransactionSigner:
    def __init__(self, private_key):
        self.private_key = private_key
    
    def sign_transaction(self, transaction):
        # Create transaction hash
        tx_hash = self._create_transaction_hash(transaction)
        
        # Sign the hash
        signature = self.private_key.sign(
            tx_hash,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA256()
        )
        
        return signature
    
    def _create_transaction_hash(self, transaction):
        # Create deterministic hash of transaction
        tx_string = json.dumps(transaction, sort_keys=True)
        return hashlib.sha256(tx_string.encode()).digest()
    
    def verify_signature(self, transaction, signature, public_key):
        # Verify transaction signature
        tx_hash = self._create_transaction_hash(transaction)
        
        try:
            public_key.verify(
                signature,
                tx_hash,
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                hashes.SHA256()
            )
            return True
        except Exception:
            return False

Backup and Recovery

Backup Strategies

Multi-Location Backup

class BackupManager:
    def __init__(self):
        self.backup_locations = []
        self.encryption_key = None
    
    def add_backup_location(self, location_type, location_path):
        self.backup_locations.append({
            'type': location_type,
            'path': location_path,
            'encrypted': True
        })
    
    def create_backup(self, wallet_data):
        # Encrypt wallet data
        encrypted_data = self._encrypt_wallet_data(wallet_data)
        
        # Create backup in multiple locations
        for location in self.backup_locations:
            self._create_backup_file(encrypted_data, location)
    
    def _encrypt_wallet_data(self, wallet_data):
        # Encrypt sensitive wallet data
        f = Fernet(self.encryption_key)
        encrypted_data = f.encrypt(json.dumps(wallet_data).encode())
        return encrypted_data
    
    def _create_backup_file(self, encrypted_data, location):
        # Create backup file in specified location
        if location['type'] == 'local':
            self._save_local_backup(encrypted_data, location['path'])
        elif location['type'] == 'cloud':
            self._save_cloud_backup(encrypted_data, location['path'])
        elif location['type'] == 'hardware':
            self._save_hardware_backup(encrypted_data, location['path'])

Recovery Procedures

class WalletRecovery:
    def __init__(self, backup_manager):
        self.backup_manager = backup_manager
    
    def recover_wallet(self, recovery_method, recovery_data):
        if recovery_method == 'mnemonic':
            return self._recover_from_mnemonic(recovery_data)
        elif recovery_method == 'private_key':
            return self._recover_from_private_key(recovery_data)
        elif recovery_method == 'backup_file':
            return self._recover_from_backup(recovery_data)
        else:
            raise ValueError("Unknown recovery method")
    
    def _recover_from_mnemonic(self, mnemonic_phrase):
        # Recover wallet from mnemonic phrase
        private_key = self._derive_key_from_mnemonic(mnemonic_phrase)
        return self._reconstruct_wallet(private_key)
    
    def _recover_from_private_key(self, private_key):
        # Recover wallet from private key
        return self._reconstruct_wallet(private_key)
    
    def _recover_from_backup(self, backup_file_path):
        # Recover wallet from backup file
        encrypted_data = self._load_backup_file(backup_file_path)
        wallet_data = self._decrypt_wallet_data(encrypted_data)
        return self._reconstruct_wallet_from_data(wallet_data)

Threat Protection

Phishing Protection

Address Verification

class AddressVerifier:
    def __init__(self):
        self.known_addresses = set()
        self.suspicious_patterns = [
            r'[0-9]+[a-z]+[0-9]+',  # Mixed numbers and letters
            r'[a-z]+[0-9]+[a-z]+',  # Alternating pattern
        ]
    
    def verify_address(self, address):
        # Check if address is in known good list
        if address in self.known_addresses:
            return True, "Address verified"
        
        # Check for suspicious patterns
        for pattern in self.suspicious_patterns:
            if re.search(pattern, address, re.IGNORECASE):
                return False, "Suspicious address pattern"
        
        # Additional verification checks
        if self._check_address_format(address):
            return True, "Address format valid"
        else:
            return False, "Invalid address format"
    
    def _check_address_format(self, address):
        # Validate address format based on cryptocurrency type
        return len(address) >= 26 and len(address) <= 62

Transaction Confirmation

class TransactionConfirmation:
    def __init__(self):
        self.confirmation_methods = ['email', 'sms', 'authenticator']
    
    def send_confirmation(self, transaction, user_preferences):
        confirmation_code = self._generate_confirmation_code()
        
        for method in user_preferences['confirmation_methods']:
            if method == 'email':
                self._send_email_confirmation(transaction, confirmation_code)
            elif method == 'sms':
                self._send_sms_confirmation(transaction, confirmation_code)
            elif method == 'authenticator':
                self._send_authenticator_confirmation(transaction, confirmation_code)
        
        return confirmation_code
    
    def verify_confirmation(self, transaction_id, confirmation_code):
        # Verify confirmation code
        stored_code = self._get_stored_confirmation_code(transaction_id)
        return confirmation_code == stored_code

Malware Protection

Transaction Monitoring

class TransactionMonitor:
    def __init__(self):
        self.suspicious_patterns = [
            'unusual_amount',
            'unusual_recipient',
            'rapid_transactions',
            'off_hours_activity'
        ]
    
    def monitor_transaction(self, transaction, user_history):
        alerts = []
        
        # Check for unusual amounts
        if self._check_unusual_amount(transaction, user_history):
            alerts.append("Unusual transaction amount detected")
        
        # Check for unusual recipients
        if self._check_unusual_recipient(transaction, user_history):
            alerts.append("Unusual recipient address detected")
        
        # Check for rapid transactions
        if self._check_rapid_transactions(transaction, user_history):
            alerts.append("Rapid transaction sequence detected")
        
        # Check for off-hours activity
        if self._check_off_hours_activity(transaction, user_history):
            alerts.append("Off-hours transaction activity detected")
        
        return alerts
    
    def _check_unusual_amount(self, transaction, user_history):
        # Check if amount is significantly different from user's typical transactions
        typical_amount = statistics.median([tx['amount'] for tx in user_history[-10:]])
        return abs(transaction['amount'] - typical_amount) > typical_amount * 2
    
    def _check_unusual_recipient(self, transaction, user_history):
        # Check if recipient is new or unusual
        previous_recipients = set([tx['recipient'] for tx in user_history[-20:]])
        return transaction['recipient'] not in previous_recipients

Best Practices

Security Checklist

Wallet Security Checklist

  • Strong Passwords: Use complex, unique passwords
  • Two-Factor Authentication: Enable 2FA on all accounts
  • Regular Backups: Create encrypted backups regularly
  • Software Updates: Keep wallet software updated
  • Antivirus Protection: Use reputable antivirus software
  • Secure Networks: Only use secure, trusted networks
  • Transaction Verification: Always verify transaction details
  • Address Verification: Double-check recipient addresses
  • Amount Verification: Verify transaction amounts
  • Regular Monitoring: Monitor account activity regularly

Implementation Guidelines

  • Use Hardware Wallets: For large amounts, use hardware wallets
  • Diversify Storage: Don't keep all funds in one place
  • Test Recovery: Regularly test backup and recovery procedures
  • Stay Informed: Keep up with security best practices
  • Report Suspicious Activity: Report any suspicious activity immediately

Ready to protect your data? Check out our Data Protection guide or explore Compliance.