### File Hashing Example (MD5, SHA, HMAC) Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This function demonstrates how to hash a file using various algorithms provided by the native_crypto package. It takes a file path, a hashing algorithm instance, and an expected hash value for assertion. The function reads the file in chunks and pipes it through the hashing stream. ```dart Future testFileHashing( String filePath, NCryptoHashStream hash, String assertValue, ) async { await File(filePath).openRead().pipe(hash); log("hashing result: $hash"); assert(hash.toString() == assertValue); } ``` -------------------------------- ### Download File Example Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This function downloads a file from a given URL and saves it to a specified path. It utilizes HttpClient for network requests and IOSink for file writing. Error handling is included to ensure resources are closed properly. ```dart Future downloadFile(String url, String savePath) async { var httpClient = HttpClient(); IOSink? fileSink; try { var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); // 建立檔案物件 fileSink = File(savePath).openWrite(); await response.pipe(fileSink); fileSink.close(); } finally { httpClient.close(); fileSink?.close(); } } ``` -------------------------------- ### AES Encryption and Decryption Example Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This section illustrates AES encryption and decryption of a file using the `native_crypto` package. It demonstrates how to generate a new AES key and IV, encrypt the file content, and then decrypt it back. The example also includes calculating the MD5 hash of the original file to verify the integrity after decryption. ```dart log("start encrypt file..."); var encryptedFileSink = File(aesEncryptedFile).openWrite(); var md5 = NCrypto.md5(); await File(srcFile) .openRead() .transform(md5) .transform(cipher.encrypt(key, iv)) .pipe(encryptedFileSink); await encryptedFileSink.close(); log( "encrypted: file size = ${File(aesEncryptedFile).lengthSync()}, md5: $md5}", ); assert(md5.hexString == '16913d991805bdb654969be0a9716729'); log("start decrypt file..."); ``` -------------------------------- ### Perform Various Cryptographic Hashes Source: https://pub.dev/packages/native_crypto/example Demonstrates the usage of multiple hashing algorithms (MD5, SHA1, SHA224, SHA256, SHA384, SHA512) from the native_crypto package on a downloaded file. Includes platform-specific checks for SHA224 on Windows. ```dart await testFileHashing( srcFile, NCrypto.md5(), "16913d991805bdb654969be0a9716729", ); await testFileHashing( srcFile, NCrypto.sha1(), "11107dad62edc630b33346fb12bf4aa4b45d4656", ); if (!Platform.isWindows) { // Windows not support SHA224 await testFileHashing( srcFile, NCrypto.sha224(), "61647969617cd0fff45dcd51f1d76fb93e372248a91c356b13f5d640", ); } await testFileHashing( srcFile, NCrypto.sha256(), "44fca133cee30b10b8d7a8c51fc6ee2e03e16096a9bb224441a0643d0798784c", ); await testFileHashing( srcFile, NCrypto.sha384(), "567749feb72aabcf76ab1a1d557e6488d375d0e04680158a9a85f10fb0a5d5a400bc65eef254a9d502f671511feac7e8", ); await testFileHashing( srcFile, NCrypto.sha512(), "a7ed41732b650fc12f8bb3a51a44e2c735ddd7b551c940c7a3fb6075e2b6bff392114ea3133b43bb9cd67a0b79bb4b495735f557b629c13e35806c2d8ea97f7e", ); ``` -------------------------------- ### Perform HMAC Calculations Source: https://pub.dev/packages/native_crypto/example Demonstrates the usage of HMAC algorithms (HMAC-MD5, HMAC-SHA1, HMAC-SHA224, HMAC-SHA256, HMAC-SHA384, HMAC-SHA512) with a predefined key on a downloaded file. Includes platform-specific checks for HMAC-SHA224 on Windows. ```dart await testFileHashing( srcFile, NCrypto.hmacMd5(hmacKey), "7bd26bc708e4eb3c06496ca07e5fd8aa", ); await testFileHashing( srcFile, NCrypto.hmacSha1(hmacKey), "140d7e7d9ac0637dd7ddd1b2234576e8ffa88088", ); if (!Platform.isWindows) { await testFileHashing( srcFile, NCrypto.hmacSha224(hmacKey), "8c4b1e8ab8aae7155adb403effae046025e20bbf73c3744bc97df5d3", ); } await testFileHashing( srcFile, NCrypto.hmacSha256(hmacKey), "a336bc9bcb00f24a73f21faa696be6553facb2358ac4c73fea5b091c52cf90c5", ); await testFileHashing( srcFile, NCrypto.hmacSha384(hmacKey), "591437357a6147d95bde98c9db2655a4694e217cdcac9819cf9d5a431e928c17c5da3aae557d5dc0be8b521d05d1d8e3", ); await testFileHashing( srcFile, NCrypto.hmacSha512(hmacKey), "67d5f1e8ab311819a5c7b4985604b8a5b581154b4fc636c55794bc86b375b5fc06e3a80d9dc0464f5a0611849463f5d1886d47152ae8a98908d5615ca66bd1ee", ); ``` -------------------------------- ### Install libssl-dev for Linux Source: https://pub.dev/packages/native_crypto/index For the Linux platform, ensure that the 'libssl-dev' package is installed on your system. This is a prerequisite for the native_crypto package to function correctly on Linux environments. ```bash sudo apt install libssl-dev ``` -------------------------------- ### AES CBC Encryption and Decryption Source: https://pub.dev/packages/native_crypto/example Demonstrates AES CBC mode encryption and decryption using the native_crypto package. It generates a new key and IV, encrypts a file, and then prepares for decryption. The process involves piping data through transformations. ```dart var cipher = NCrypto.aesCbc; var key = cipher.newKey256(); var iv = cipher.newIV(); //var iv = []; //aesMode.newIV(); log("start encrypt file..."); var encryptedFileSink = File(aesEncryptedFile).openWrite(); var md5 = NCrypto.md5(); await File(srcFile) .openRead() .transform(md5) .transform(cipher.encrypt(key, iv)) .pipe(encryptedFileSink); await encryptedFileSink.close(); log( "encrypted: file size = ${File(aesEncryptedFile).lengthSync()}, md5: $md5}", ); assert(md5.hexString == '16913d991805bdb654969be0a9716729'); log("start decrypt file..."); ``` -------------------------------- ### Initialize and Build Flutter App with Test Execution Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This snippet shows the `initState` and `build` methods of a Flutter widget. `initState` is typically used for one-time initializations. The `build` method sets up the basic MaterialApp and Scaffold structure, and crucially, it calls the `test()` function to initiate cryptographic tests when the widget is built. A commented-out line suggests a potential for running tests multiple times. ```dart @override void initState() { super.initState(); } @override Widget build(BuildContext context) { //testMultiTimes(); test(); return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Native Packages')), body: Center(child: Text("ccc")), ), ); } ``` -------------------------------- ### File Comparison Utility Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example A utility function to compare two files for equality. It reads both files into byte arrays and checks if their lengths are the same. If the lengths match, it iterates through the bytes, returning false if any differing byte is found. This function is crucial for verifying data integrity after cryptographic operations. ```dart Future isFileEqual(String file1, String file2) async { final bytes1 = await File(file1).readAsBytes(); final bytes2 = await File(file2).readAsBytes(); if (bytes1.length != bytes2.length) return false; for (int i = 0; i < bytes1.length; i++) { var ch1 = bytes1[i]; var ch2 = bytes2[i]; if (ch1 != ch2) { return false; } } return true; } ``` -------------------------------- ### Convert Data to MD5 Hash Source: https://pub.dev/packages/native_crypto/example Converts arbitrary byte data into its MD5 hash representation using the native_crypto package. This function is useful for generating checksums or verifying data integrity. ```dart log("md5 convert A => ${NCrypto.md5().convert(utf8.encode("test"))}"); log("md5 convert B => ${NCrypto.md5().convert(utf8.encode("abcd"))}"); ``` -------------------------------- ### Calculate MD5 of a String Source: https://pub.dev/packages/native_crypto/index This example shows how to compute the MD5 hash of a string. The string is first encoded to UTF-8 bytes, then passed to the NCrypto.md5().convert() method. ```dart log("md5 of string => ${NCrypto.md5().convert(utf8.encode("test"))}"); ``` -------------------------------- ### Install native_crypto Package Source: https://pub.dev/packages/native_crypto/versions/0 Instructions to add the native_crypto package to your Flutter project's pubspec.yaml file. It's crucial to include the dependency_overrides section to avoid build errors on Windows and Linux. ```yaml dependencies: native_crypto: dependency_overrides: ## IMPORTANT !!! jni: git: url: https://github.com/jakky1/native.git ref: only_jni ``` -------------------------------- ### Install native_crypto Package Source: https://pub.dev/packages/native_crypto/index To integrate the native_crypto package into your project, add the specified dependency to your pubspec.yaml file. Crucially, include the dependency_overrides section for the 'jni' package to avoid build errors on Windows and Linux. ```yaml dependencies: native_crypto: dependency_overrides: ## IMPORTANT !!! jni: git: url: https://github.com/jakky1/native.git ref: only_jni ``` -------------------------------- ### AES-CBC Encryption and Decryption Example Source: https://pub.dev/packages/native_crypto/index Encrypts and decrypts a file using the AES-CBC algorithm. Requires a secure randomly generated 256-bit key and a 16-byte IV. Reads from a source file and pipes the transformed data to a file sink. ```dart // select AES-CBC algorithm var cipher = NCrypto.aesCbc; // secure randomly generate 32-bytes secret key for AES-256 var key = cipher.newKey256(); // secure randomly generate 16-bytes IV (nonce) var iv = cipher.newIV(); await File(srcFile) .openRead() .transform(cipher.encrypt(key, iv)) // encrypt data .pipe(fileSink); await File(srcFile) .openRead() .transform(cipher.decrypt(key, iv)) // decrypt data .pipe(fileSink); ``` -------------------------------- ### Decrypt File with AES and Verify Integrity Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This snippet demonstrates decrypting an AES-encrypted file using a provided key and IV. It then compares the decrypted file with the original source file to ensure integrity. The process involves opening file streams, transforming data with the cipher, and piping it to a sink. It also includes a helper function to compare two files byte by byte. ```dart var decryptedFileSink = File(aesDecryptedFile).openWrite(); await File( aesEncryptedFile, ).openRead().transform(cipher.decrypt(key, iv)).pipe(decryptedFileSink); await decryptedFileSink.close(); log("decrypted: file size = ${File(aesDecryptedFile).lengthSync()}"); var sameA = await isFileEqual(srcFile, aesDecryptedFile); log("decrypted sameA: $sameA"); assert(sameA); var sameB = await isFileEqual(srcFile, aesEncryptedFile); log("encrypted sameB: $sameB"); assert(!sameB); ``` -------------------------------- ### Run Cryptographic Tests Multiple Times Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example This function is designed to execute a `test` function repeatedly, specifically 100 times. This is useful for performance testing or ensuring the stability of cryptographic operations under repeated execution. It uses an asynchronous loop to await each test execution. ```dart Future testMultiTimes() async { for (int i = 0; i < 100; i++) { await test(); } } ``` -------------------------------- ### HMAC Key Definition Source: https://pub.dev/packages/native_crypto/versions/0.8.0/example Defines a byte array representing a 256-bit (32-byte) key, likely intended for use with HMAC-SHA256 or similar cryptographic functions. This key is declared as a global variable and is presented in hexadecimal format. ```dart var hmacKey = [ 0x34, 0x41, 0xD2, 0x60, 0x11, 0x97, 0xCE, 0xCE, 0x50, 0x6C, 0x68, 0xD5, 0x63, 0x42, 0xC2, 0xD5, 0x83, 0x1D, 0x27, 0xC5, 0x08, 0xCC, 0x0C, 0x07, 0x2F, 0xCE, 0x7E, 0x3D, 0x6D, 0x42, 0x3A, 0x99, ]; ``` -------------------------------- ### Stream HMAC Calculation Source: https://pub.dev/packages/native_crypto/index Similar to MD5 hashing, HMAC calculations can also be performed on streams. This example shows passing the NCrypto.hmacSha512(key) transformer into the response stream's transform method. ```dart var hmac = NCrypto.hmacSha512(key); await response.transform(hmac).pipe(fileSink); // pass into transform() ``` -------------------------------- ### Calculate File MD5 Hash Source: https://pub.dev/packages/native_crypto/index This example demonstrates how to calculate the MD5 hash of a file using the native_crypto package. The NCrypto.md5() object is piped directly into the file's openRead stream, and the resulting hash can be accessed as a hex string or byte array. ```dart var hash = NCrypto.md5(); // use MD5 algorithm await File(filePath).openRead().pipe(hash); log("hashing result: $hash"); // file MD5 hex string Uint8List? bytes = hash.bytes; // file MD5 result (byte array) // `hash.bytes` will be `null` if stream not closed ``` -------------------------------- ### Android Implementation Variable Declaration (Dart) Source: https://pub.dev/packages/native_crypto/score This snippet shows the declaration of a variable `_SecretKeySpec` within the Android implementation file. It is part of the JNI (Java Native Interface) setup for accessing Android's cryptographic functionalities. The variable name violates lowerCamelCase conventions as per Dart lints. ```dart final _SecretKeySpec = jni.JClass.forName( ``` -------------------------------- ### Selecting AES Algorithm Modes Source: https://pub.dev/packages/native_crypto/versions/0 Shows how to select different AES algorithm modes provided by the NCrypto library. It highlights the recommended secure modes and notes the less secure AES-ECB. ```dart var cipher = NCrypto.aesCbc; // AES-CBC, safe, suggested var cipher = NCrypto.aesEcb; // AES-ECB, not safe var cipher = NCrypto.aesCfb; // AES-CFB, safe var cipher = NCrypto.aesCtr; // AES-CTR, safe & fast (Windows not support) ``` -------------------------------- ### SHA Algorithm Options Source: https://pub.dev/packages/native_crypto/versions/0 Lists the available SHA hashing algorithms supported by the native_crypto package. Replace `NCrypto.md5()` with the desired SHA algorithm. ```dart NCrypto.md5() NCrypto.sha1() NCrypto.sha224() // Windows not support NCrypto.sha256() NCrypto.sha384() NCrypto.sha512() ``` -------------------------------- ### HMAC Algorithm Options Source: https://pub.dev/packages/native_crypto/versions/0 Provides a list of available HMAC algorithms supported by the native_crypto package. Replace `NCrypto.hmacSha512(key)` with the desired HMAC algorithm and key. ```dart NCrypto.hmacMd5(key) // HMAC-MD5 NCrypto.hmacSha1(key) // HMAC-SHA1 NCrypto.hmacSha224(key) // HMAC-SHA224 NCrypto.hmacSha256(key) // HMAC-SHA256 NCrypto.hmacSha384(key) // HMAC-SHA384 NCrypto.hmacSha512(key) // HMAC-SHA512 ``` -------------------------------- ### Encrypt File with AES-ECB (No IV) Source: https://pub.dev/packages/native_crypto/versions/0 Demonstrates how to encrypt a file using the AES-ECB algorithm. It is crucial to note that AES-ECB does not use an Initialization Vector (IV); attempting to provide one will result in an exception. ```dart var cipher = NCrypto.aesEcb; var key = cipher.newKey256(); //var iv = cipher.newIV(); // don't use IV in AES-ECB await File(srcFile) .openRead() .transform(cipher.encrypt(key)) // don't pass `IV` in AES-ECB .pipe(fileSink); ``` -------------------------------- ### AES Key Generation Options Source: https://pub.dev/packages/native_crypto/versions/0 Demonstrates the different methods for securely generating secret keys for AES encryption. Supports key sizes for AES-128, AES-192, and AES-256. ```dart var key = cipher.newKey128(); // secure randomly generate 16-bytes secret key for AES-128 var key = cipher.newKey192(); // secure randomly generate 24-bytes secret key for AES-192 var key = cipher.newKey256(); // secure randomly generate 32-bytes secret key for AES-256 ``` -------------------------------- ### Download and MD5 Hash File Source: https://pub.dev/packages/native_crypto/index This code snippet shows how to download a file and simultaneously calculate its MD5 hash. The NCrypto.md5() transformer is applied to the response stream before piping it to a file sink, allowing for efficient processing. ```dart String url = "https://..."; var httpClient = HttpClient(); var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); var hash = NCrypto.md5(); // use MD5 algorithm var fileSink = File(savePath).openWrite(); await response.transform(hash).pipe(fileSink); // pass into transform() fileSink.close(); log("file downloaded. MD5: $hash"); // file MD5 hex string ``` -------------------------------- ### Calculate MD5 Hash of a File Source: https://pub.dev/packages/native_crypto/versions/0 Demonstrates how to calculate the MD5 hash of a file using the native_crypto package. The `NCrypto.md5()` object can be piped directly from a file stream or used within a transform operation. ```dart var hash = NCrypto.md5(); // use MD5 algorithm await File(filePath).openRead().pipe(hash); log("hashing result: $hash"); // file MD5 hex string Uint8List? bytes = hash.bytes; // file MD5 result (byte array) // `hash.bytes` will be `null` if stream not closed ``` ```dart String url = "https://..."; var httpClient = HttpClient(); var request = await httpClient.getUrl(Uri.parse(url)); var response = await request.close(); var hash = NCrypto.md5(); // use MD5 algorithm var fileSink = File(savePath).openWrite(); await response.transform(hash).pipe(fileSink); // pass into transform() fileSink.close(); log("file downloaded. MD5: $hash"); // file MD5 hex string ``` ```dart log("md5 of string => ${NCrypto.md5().convert(utf8.encode("test"))}"); ``` -------------------------------- ### Encrypt File with AES-CBC Source: https://pub.dev/packages/native_crypto/versions/0 Encrypts a file using the AES-CBC algorithm. It requires a securely generated 256-bit key and a 16-byte Initialization Vector (IV). The encryption is performed by transforming the file's read stream. ```dart // select AES-CBC algorithm var cipher = NCrypto.aesCbc; // secure randomly generate 32-bytes secret key for AES-256 var key = cipher.newKey256(); // secure randomly generate 16-bytes IV (nonce) var iv = cipher.newIV(); await File(srcFile) .openRead() .transform(cipher.encrypt(key, iv)) // encrypt data .pipe(fileSink); ``` -------------------------------- ### Add native_crypto Dependency (Flutter) Source: https://pub.dev/packages/native_crypto/install This command adds the native_crypto package as a dependency to your Flutter project. It ensures the package is available for use in your Dart code. ```bash flutter pub add native_crypto ``` -------------------------------- ### Encode and Decode Bytes with AES-CBC Source: https://pub.dev/packages/native_crypto/versions/0 Provides a method for directly encoding and decoding byte lists using the AES-CBC algorithm. This is useful for in-memory cryptographic operations without file I/O. ```dart List data = [...]; List encryptedBytes = NCrypto.aesCbc.encrypt(key, iv).convert(data); List decryptedBytes = NCrypto.aesCbc.decrypt(key, iv).convert(encryptedBytes); // `data` should equal to `decryptedBytes` ``` -------------------------------- ### Calculate HMAC-SHA512 of a File Source: https://pub.dev/packages/native_crypto/versions/0 Shows how to compute the HMAC-SHA512 hash of a file using a newly generated secure random key. The HMAC object can be piped from file streams or used in transform operations. ```dart var key = NCrypto.newHMacKey(); // create new secure random key for HMAC var hmac = NCrypto.hmacSha512(key); await File(filePath).openRead().pipe(hmac); log("HMac result: $hmac"); // file HMAC-SHA512 hex string Uint8List? bytes = hmac.bytes; // file HMAC-SHA512 result (byte array) ``` ```dart var hmac = NCrypto.hmacSha512(key); await response.transform(hmac).pipe(fileSink); // pass into transform() ``` -------------------------------- ### Import native_crypto in Dart Source: https://pub.dev/packages/native_crypto/install This import statement allows you to access the functionality provided by the native_crypto package within your Dart or Flutter application. ```dart import 'package:native_crypto/native_crypto.dart'; ``` -------------------------------- ### Calculate File HMAC-SHA512 Source: https://pub.dev/packages/native_crypto/index This snippet demonstrates calculating an HMAC-SHA512 hash for a file. A new secure random key is generated using NCrypto.newHMacKey(), and then the NCrypto.hmacSha512() function is used to process the file stream. ```dart var key = NCrypto.newHMacKey(); // create new secure random key for HMAC var hmac = NCrypto.hmacSha512(key); await File(filePath).openRead().pipe(hmac); log("HMac result: $hmac"); // file HMAC-SHA512 hex string Uint8List? bytes = hmac.bytes; // file HMAC-SHA512 result (byte array) ``` -------------------------------- ### Decrypt File with AES-CBC Source: https://pub.dev/packages/native_crypto/versions/0 Decrypts a file that was previously encrypted with the AES-CBC algorithm. It uses the same key and Initialization Vector (IV) that were used during encryption. The decryption transforms the file's read stream. ```dart await File(srcFile) .openRead() .transform(cipher.decrypt(key, iv)) // decrypt data .pipe(fileSink); ``` -------------------------------- ### Android Implementation Constructor ID Declaration (Dart) Source: https://pub.dev/packages/native_crypto/score This code snippet illustrates the declaration of `_SecretKeySpec_constructor`, which is used to retrieve the constructor ID for a JNI class. This is a common pattern when interacting with native Java code from Dart using the JNI library. The variable name does not follow lowerCamelCase conventions. ```dart final _SecretKeySpec_constructor = _SecretKeySpec.constructorId( ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.