cryptdart 0.1.6 copy "cryptdart: ^0.1.6" to clipboard
cryptdart: ^0.1.6 copied to clipboard

CryptDart is a unified cryptography library for Dart, providing easy-to-use interfaces for symmetric and asymmetric encryption, digital signatures (including ECDSA), and key management. Built on Point [...]

example/main.dart

/// Comprehensive CryptDart Example
/// 
/// This example demonstrates all the features of the CryptDart library:
/// - Symmetric encryption (AES, ChaCha20, DES)
/// - Asymmetric encryption (RSA)
/// - Digital signatures (HMAC, RSA signatures)
/// - ECDH key exchange
/// - Secure communication sessions
/// 
/// Run with: dart run example/main.dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:cryptdart/cryptdart.dart';

void main() async {
  print('šŸ”’ CryptDart - Comprehensive Cryptography Example\n');
  
  await demonstrateSymmetricEncryption();
  await demonstrateAsymmetricEncryption();
  await demonstrateDigitalSignatures();
  await demonstrateECDHKeyExchange();
  await demonstrateSecureSessions();
  
  print('\nšŸŽ‰ All cryptographic operations completed successfully!');
}

/// Demonstrates symmetric encryption with AES, ChaCha20, and DES
Future<void> demonstrateSymmetricEncryption() async {
  print('šŸ” === SYMMETRIC ENCRYPTION DEMO ===');
  
  // AES Example
  print('\nšŸ“ AES-256 Encryption:');
  final aesKey = AESCipher.generateKey();
  print('   Generated key: ${aesKey.substring(0, 16)}...');
  
  final aes = AESCipher(
    InputAESCipher(
      parent: InputSymmetricCipher(
        key: aesKey,
        parent: InputCipher(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(hours: 24)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final message = 'Confidential AES message';
  final aesEncrypted = aes.encrypt(utf8.encode(message));
  final aesDecrypted = utf8.decode(aes.decrypt(aesEncrypted));
  print('   Original: $message');
  print('   Encrypted: ${aesEncrypted.length} bytes');
  print('   Decrypted: $aesDecrypted');
  print('   āœ… AES encryption successful');
  
  // ChaCha20 Example
  print('\nšŸš€ ChaCha20 Encryption:');
  final chachaKey = ChaCha20Cipher.generateKey();
  final nonce = Uint8List.fromList([1, 2, 3, 4, 5, 6, 7, 8]);
  print('   Generated key: ${chachaKey.substring(0, 16)}...');
  
  final chacha = ChaCha20Cipher(
    InputChaCha20Cipher(
      nonce: nonce,
      parent: InputSymmetricCipher(
        key: chachaKey,
        parent: InputCipher(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(hours: 12)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final chachaMessage = 'High-performance ChaCha20 message';
  final chachaEncrypted = chacha.encrypt(utf8.encode(chachaMessage));
  final chachaDecrypted = utf8.decode(chacha.decrypt(chachaEncrypted));
  print('   Original: $chachaMessage');
  print('   Encrypted: ${chachaEncrypted.length} bytes');
  print('   Decrypted: $chachaDecrypted');
  print('   āœ… ChaCha20 encryption successful');
  
  // DES Example
  print('\nšŸ”§ DES Encryption (Legacy):');
  final desKey = DESCipher.generateKey();
  print('   Generated key: ${desKey.substring(0, 16)}...');
  
  final des = DESCipher(
    InputDESCipher(
      parent: InputSymmetricCipher(
        key: desKey,
        parent: InputCipher(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(hours: 1)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final desMessage = 'Legacy DES message';
  final desEncrypted = des.encrypt(utf8.encode(desMessage));
  final desDecrypted = utf8.decode(des.decrypt(desEncrypted));
  print('   Original: $desMessage');
  print('   Encrypted: ${desEncrypted.length} bytes');
  print('   Decrypted: $desDecrypted');
  print('   āœ… DES encryption successful');
}

/// Demonstrates asymmetric encryption with RSA
Future<void> demonstrateAsymmetricEncryption() async {
  print('\nšŸ”‘ === ASYMMETRIC ENCRYPTION DEMO ===');
  
  print('\nšŸ”’ RSA-2048 Encryption:');
  final rsaKeys = await RSACipher.generateKeyPair(bitLength: 2048);
  print('   Generated RSA key pair (2048-bit)');
  
  final rsa = RSACipher(
    InputRSACipher(
      parent: InputAsymmetricCipher(
        publicKey: rsaKeys['publicKey']!,
        privateKey: rsaKeys['privateKey']!,
        parent: InputCipher(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(days: 30)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final rsaMessage = 'Secret RSA message';
  final rsaEncrypted = await rsa.encrypt(utf8.encode(rsaMessage));
  final rsaDecrypted = utf8.decode(await rsa.decrypt(rsaEncrypted));
  print('   Original: $rsaMessage');
  print('   Encrypted: ${rsaEncrypted.length} bytes');
  print('   Decrypted: $rsaDecrypted');
  print('   āœ… RSA encryption successful');
}

/// Demonstrates digital signatures with HMAC and RSA
Future<void> demonstrateDigitalSignatures() async {
  print('\nāœļø  === DIGITAL SIGNATURES DEMO ===');
  
  // HMAC Signatures
  print('\nšŸ” HMAC Signature:');
  final hmacKey = HMACSign.generateKey();
  print('   Generated HMAC key: ${hmacKey.substring(0, 16)}...');
  
  final hmac = HMACSign(
    InputHMACSign(
      parent: InputSymmetricSign(
        key: hmacKey,
        parent: InputSign(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(hours: 6)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final contract = 'Important contract to sign';
  final hmacSignature = hmac.sign(utf8.encode(contract));
  final hmacVerified = hmac.verify(utf8.encode(contract), hmacSignature);
  print('   Document: $contract');
  print('   Signature: ${hmacSignature.sublist(0, 8)}... (${hmacSignature.length} bytes)');
  print('   Verified: $hmacVerified');
  print('   āœ… HMAC signature successful');
  
  // RSA Signatures
  print('\nšŸ”’ RSA Signature:');
  final rsaSigKeys = await RSASignatureCipher.generateKeyPair(bitLength: 2048);
  print('   Generated RSA signature key pair (2048-bit)');
  
  final rsaSign = RSASignatureCipher(
    InputRSASignatureCipher(
      parent: InputAsymmetricSign(
        publicKey: rsaSigKeys['publicKey']!,
        privateKey: rsaSigKeys['privateKey']!,
        parent: InputSign(
          parent: InputExpirationBase(
            expirationDate: DateTime.now().add(Duration(days: 365)),
            expirationTimes: null,
          ),
        ),
      ),
    ),
  );
  
  final certificate = 'Digital certificate content';
  final rsaSignature = rsaSign.sign(utf8.encode(certificate));
  final rsaVerified = rsaSign.verify(utf8.encode(certificate), rsaSignature);
  print('   Certificate: $certificate');
  print('   Signature: ${rsaSignature.sublist(0, 8)}... (${rsaSignature.length} bytes)');
  print('   Verified: $rsaVerified');
  print('   āœ… RSA signature successful');
}

/// Demonstrates ECDH key exchange
Future<void> demonstrateECDHKeyExchange() async {
  print('\nšŸ”„ === ECDH KEY EXCHANGE DEMO ===');
  
  print('\nšŸ‘„ Alice and Bob ECDH Exchange:');
  
  // Alice generates her key pair
  final aliceKeys = await ECDHKeyExchange.generateKeyPair(curve: ECCKeyUtils.secp256r1);
  final alice = ECDHKeyExchange(
    InputECDHKeyExchange(
      parent: InputKeyExchangeBase(
        algorithm: KeyExchangeAlgorithm.ecdh,
        expirationDate: DateTime.now().add(Duration(minutes: 30)),
        expirationTimes: null,
      ),
      publicKey: aliceKeys['publicKey']!,
      privateKey: aliceKeys['privateKey']!,
      curve: ECCKeyUtils.secp256r1,
    ),
  );
  print('   šŸ‘© Alice generated secp256r1 key pair');
  
  // Bob generates his key pair
  final bobKeys = await ECDHKeyExchange.generateKeyPair(curve: ECCKeyUtils.secp256r1);
  final bob = ECDHKeyExchange(
    InputECDHKeyExchange(
      parent: InputKeyExchangeBase(
        algorithm: KeyExchangeAlgorithm.ecdh,
        expirationDate: DateTime.now().add(Duration(minutes: 30)),
        expirationTimes: null,
      ),
      publicKey: bobKeys['publicKey']!,
      privateKey: bobKeys['privateKey']!,
      curve: ECCKeyUtils.secp256r1,
    ),
  );
  print('   šŸ‘Ø Bob generated secp256r1 key pair');
  
  // Both compute the same shared secret
  final aliceSharedSecret = alice.generateSharedSecret(bob.publicKey);
  final bobSharedSecret = bob.generateSharedSecret(alice.publicKey);
  
  print('   šŸ” Alice computed shared secret: ${aliceSharedSecret.substring(0, 16)}...');
  print('   šŸ” Bob computed shared secret: ${bobSharedSecret.substring(0, 16)}...');
  print('   šŸ¤ Shared secrets match: ${aliceSharedSecret == bobSharedSecret}');
  print('   āœ… ECDH key exchange successful');
}

/// Demonstrates secure communication sessions
Future<void> demonstrateSecureSessions() async {
  print('\n🌐 === SECURE COMMUNICATION DEMO ===');
  
  print('\nšŸ¤ Establishing secure session between Alice and Bob...');
  
  // Alice initiates a secure session with Bob
  final aliceSession = await SecureCommunicationFactory.initiateSecureSession(
    localPeerId: 'alice@example.com',
    supportedAsymmetric: [AsymmetricCipherAlgorithm.rsa],
    supportedSymmetric: [SymmetricCipherAlgorithm.chacha20, SymmetricCipherAlgorithm.aes],
    sendToRemote: (initiationMessage) async {
      // Simulate Bob receiving Alice's message and responding
      print('   šŸ“Ø Alice sent initiation message to Bob');
      
      final bobResponse = await SecureCommunicationFactory.respondToSecureSession(
        localPeerId: 'bob@example.com',
        initiationMessage: initiationMessage,
        supportedAsymmetric: [AsymmetricCipherAlgorithm.rsa],
        supportedSymmetric: [SymmetricCipherAlgorithm.aes, SymmetricCipherAlgorithm.chacha20],
      );
      
      print('   šŸ“¬ Bob responded with negotiated parameters');
      return bobResponse.responseMessage;
    },
  );
  
  print('   šŸ”’ Secure session established!');
  print('   šŸ†” Local peer: ${aliceSession.negotiationResult.localPeerId}');
  print('   šŸ†” Remote peer: ${aliceSession.negotiationResult.remotePeerId}');
  print('   šŸ” Key exchange: ${aliceSession.negotiationResult.keyExchange}');
  print('   šŸ” Asymmetric: ${aliceSession.negotiationResult.asymmetric}');
  print('   šŸ” Symmetric: ${aliceSession.negotiationResult.symmetric}');
  print('   šŸ•’ Established: ${aliceSession.establishedAt}');
  
  // Test secure communication
  final secretMessage = 'This is a confidential message sent through secure session';
  final encryptedMessage = aliceSession.encryptData(utf8.encode(secretMessage));
  final decryptedMessage = utf8.decode(aliceSession.decryptData(encryptedMessage));
  
  print('   šŸ“ Original: $secretMessage');
  print('   šŸ”’ Encrypted: ${encryptedMessage.length} bytes');
  print('   šŸ“– Decrypted: $decryptedMessage');
  print('   šŸ” Messages match: ${secretMessage == decryptedMessage}');
  print('   āœ… Secure communication successful');
}
0
likes
0
points
37
downloads

Publisher

unverified uploader

Weekly Downloads

CryptDart is a unified cryptography library for Dart, providing easy-to-use interfaces for symmetric and asymmetric encryption, digital signatures (including ECDSA), and key management. Built on PointyCastle and BasicUtils, LGPL-3.0.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

barrel_files_annotation, basic_utils, crypto, meta, path, pointycastle

More

Packages that depend on cryptdart