James vor 9 Monaten
Ursprung
Commit
c443006e21
3 geänderte Dateien mit 57 neuen und 2 gelöschten Zeilen
  1. 55 1
      lib/util/hexUtils.dart
  2. 1 1
      pubspec.lock
  3. 1 0
      pubspec.yaml

+ 55 - 1
lib/util/hexUtils.dart

@@ -1,7 +1,8 @@
 import 'dart:convert' show utf8;
 import 'dart:typed_data';
-
 import 'package:convert/convert.dart' show hex;
+import "package:pointycastle/digests/keccak.dart";
+
 
 bool isHexPrefixed(String str) {
   ArgumentError.checkNotNull(str);
@@ -221,3 +222,56 @@ String dec2hex(String decString) {
 
 
 
+
+
+/// ----- to Hash -----
+/// 注意:Hash256 和 Keccak256 其实不一样,
+/// 但由于最早接触 Ethereum 相关代码,其中 Hash 使用的是 Keccak256,
+/// 造成App其他地方的 Hash 也都沿用了 Keccak256。
+/// 历史原因,不做修改。[2023-12-15 James.Zhang]
+
+String toHash(String anyString) {
+  return toKeccak256(anyString);
+}
+
+String toKeccak256(String anyString, [int bitLength = 256]) {
+  var keccak = KeccakDigest(bitLength);
+  keccak.update(
+    Uint8List.fromList(anyString.codeUnits),
+    0,
+    anyString.codeUnits.length,
+  );
+
+  var out = Uint8List(bitLength ~/ 8);
+  keccak.doFinal(out, 0);
+
+  return _uint8ListToHex(out);
+}
+
+/// Character `0`.
+const int _zero = 0x30;
+/// Character `a`.
+const int _a = 0x61;
+
+String _uint8ListToHex(List<int> bytes) {
+  final buffer = Uint8List(bytes.length * 2);
+
+  int bufferIndex = 0;
+  for (var i = 0; i < bytes.length; i++) {
+    var byte = bytes[i];
+
+    // The bitwise arithmetic here is equivalent to `byte ~/ 16` and `byte % 16`
+    // for valid byte values, but is easier for dart2js to optimize given that
+    // it can't prove that [byte] will always be positive.
+    buffer[bufferIndex++] = _codeUnitForDigit((byte & 0xF0) >> 4);
+    buffer[bufferIndex++] = _codeUnitForDigit(byte & 0x0F);
+  }
+
+  return String.fromCharCodes(buffer);
+}
+
+/// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit
+/// [digit].
+int _codeUnitForDigit(int digit) =>
+    digit < 10 ? digit + _zero : digit + _a - 10;
+

+ 1 - 1
pubspec.lock

@@ -601,7 +601,7 @@ packages:
     source: hosted
     version: "2.1.8"
   pointycastle:
-    dependency: transitive
+    dependency: "direct main"
     description:
       name: pointycastle
       sha256: "4be0097fcf3fd3e8449e53730c631200ebc7b88016acecab2b0da2f0149222fe"

+ 1 - 0
pubspec.yaml

@@ -23,6 +23,7 @@ dependencies:
   cross_file: ^0.3.3+8
   file_selector: ^1.0.3
   shared_preferences: ^2.2.2
+  pointycastle: ^3.9.1
 
 dev_dependencies:
   build_runner: ^2.4.8