Last active
May 16, 2024 09:47
-
-
Save iamEtornam/31f9c984d3b76f5d49ad89165d17abe8 to your computer and use it in GitHub Desktop.
How to hash a large video file in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'dart:convert'; | |
import 'dart:crypto'; | |
import 'package:file/file.dart'; | |
import 'package:stream_transform/stream_transform.dart'; | |
///a function that takes a File object and a chosen hashing algorithm (e.g., SHA-256) | |
Future<String> hashFile(File file, Digest digest, int chunkSize) async { | |
final sink = AccumulatorSink<List<int>>(); | |
await file.openRead().pipe(chunkStream(file, chunkSize)).pipe(transform(digest)); | |
final bytes = await sink.value; | |
return convert.base64Encode(bytes); // Base64 encoding for String output | |
} | |
///a helper function to split the file into smaller chunks: | |
Stream<List<int>> chunkStream(File file, int chunkSize) async* { | |
final bytes = await file.readAsBytes(); | |
for (var i = 0; i < bytes.length; i += chunkSize) { | |
final chunk = bytes.sublist(i, min(i + chunkSize, bytes.length)); | |
yield chunk; | |
} | |
} | |
Future<void> main() async { | |
final file = File('path/to/your/video.mp4'); // Replace with your file path | |
final digest = SHA256(); | |
final chunkSize = 1024 * 1024; // 1 MB chunks (adjust as needed) | |
try { | |
final hash = await hashFile(file, digest, chunkSize); | |
print('Hash of the video: $hash'); | |
} on Exception catch (e) { | |
print('Error hashing file: $e'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
dependencies: | |
crypto: ^3.0.1 | |
file: ^0.6.6 | |
stream_transform: ^2.2.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment