From 9c3e6c3d33a12761d38c1cf15e1b06b0938b60cc Mon Sep 17 00:00:00 2001 From: Pointcheval Hugo Date: Fri, 18 Dec 2020 13:51:45 +0100 Subject: [PATCH] Add hash function implementation --- lib/src/digest.dart | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 lib/src/digest.dart diff --git a/lib/src/digest.dart b/lib/src/digest.dart new file mode 100644 index 0000000..80d8805 --- /dev/null +++ b/lib/src/digest.dart @@ -0,0 +1,41 @@ +// Copyright (c) 2020 +// Author: Hugo Pointcheval + +import 'dart:typed_data'; + +import 'exceptions.dart'; +import 'platform.dart'; +import 'utils.dart'; + +enum HashAlgorithm { SHA1, SHA128, SHA256, SHA512 } + +/// Represents message digest, or hash function. +class MessageDigest { + HashAlgorithm _algo; + + /// Returns the standard algorithm name for this digest + HashAlgorithm get algorithm => _algo; + + /// Returns true if digest is initialized + bool get isInitialized => (_algo != null); + + /// Creates [MessageDigest] with a specific algorithm + MessageDigest(HashAlgorithm algorithm) { + _algo = algorithm; + } + + /// Creates [MessageDigest] from the name of an algorithm + MessageDigest.getInstance(String algorithm) { + _algo = Utils.getHashAlgorithm(algorithm); + } + + /// Hashes a message + Future digest(Uint8List data) async { + if (!isInitialized) { + throw DigestInitException('Digest not properly initialized.'); + } + + Uint8List hash = await Platform().digest(data, _algo); + return hash; + } +}