Flutter哈希计算插件hashlib的使用

发布于 1周前 作者 caililin 来自 Flutter

Flutter哈希计算插件hashlib的使用

简介

hashlib 是一个为Dart设计的库,它包含了多种安全哈希函数、校验和生成器以及密钥派生算法。这些算法经过优化,能够高效地运行在Dart环境中。以下是关于如何使用 hashlib 插件进行哈希计算的详细指南。

依赖项

功能特性

块哈希算法

Algorithm Available methods Source
MD2 md2, md2sum RFC-1319
MD4 md4, md4sum RFC-1320

密码/密钥派生算法

Algorithm Available methods Source
Argon2 Argon2, argon2d, argon2i, argon2id, argon2Verify RFC-9106
PBKDF2 PBKDF2, pbkdf2, #.pbkdf2 RFC-8081

消息认证码(MAC)生成器

Algorithms Available methods Source
HMAC HMAC, #.hmac RFC-2104
Poly1305 Poly1305, poly1305, poly1305auth RFC-8439

OTP生成(用于双因素认证)

Algorithms Available methods Source
HOTP HOTP RFC-4226
TOTP TOTP RFC-6238

其他哈希算法

Algorithms Available methods Source
CRC crc16, crc32, crc64 Wikipedia
Alder32 alder32 Wikipedia

随机算法

随机数生成器

通过 HashlibRandom 提供:

  • secure
  • system
  • keccak
  • sha256
  • md5
  • xxh64
  • sm3

UUID生成器

通过 uuid 提供:

  • v1
  • v3
  • v4
  • v5
  • v6
  • v7
  • v8

示例代码

Hashilb Example

import 'package:hashlib/codecs.dart';
import 'package:hashlib/hashlib.dart';

void main() {
  var text = "Happy Hashing!";
  print("text => $text");

  final key = "password";
  final salt = "some salt";
  print("key => $key");
  print("salt => $salt");
  print('');

  final pw = key.codeUnits;
  final iv = salt.codeUnits;

  // Example of hash-code generations
  print('XXH32 => ${xxh32code(text)}');
  print('CRC32 => ${crc32code(text)}');
  print('Alder32 => ${alder32code(text)}');
  print('CRC16 => ${crc16code(text)}');
  print('');

  // Examples of Hash generation
  print('CRC64 => ${crc64sum(text)}');
  print('XXH64 => ${xxh64sum(text)}');
  print('XXH3 => ${xxh3sum(text)}');
  print('XXH128 => ${xxh128sum(text)}');
  print('MD2 => ${md2.string(text)}');
  print('MD4 => ${md4.string(text)}');
  print('MD5 => ${md5.string(text)}');
  print('SHA-1 => ${sha1.string(text)}');
  print('SHA-224 => ${sha224.string(text)}');
  print('SHA-256 => ${sha256.string(text)}');
  print('SHA-384 => ${sha384.string(text)}');
  print('SHA-512 => ${sha512.string(text)}');
  print('SHA-512/224 => ${sha512t224.string(text)}');
  print('SHA-512/256 => ${sha512t256.string(text)}');
  print('SHA3-224 => ${sha3_224.string(text)}');
  print('SHA3-256 => ${sha3_256.string(text)}');
  print('SHA3-384 => ${sha3_384.string(text)}');
  print('SHA3-512 => ${sha3_512.string(text)}');
  print('Keccak-224 => ${keccak224.string(text)}');
  print('Keccak-256 => ${keccak256.string(text)}');
  print('Keccak-384 => ${keccak384.string(text)}');
  print('Keccak-512 => ${keccak512.string(text)}');
  print('SHAKE-128 => ${shake128.of(20).string(text)}');
  print('SHAKE-256 => ${shake256.of(20).string(text)}');
  print('BLAKE2s-256 => ${blake2s256.string(text)}');
  print('BLAKE2b-512 => ${blake2b512.string(text)}');
  print('SM3] => ${sm3.string(text)}');
  print('');

  // Examples of MAC generations
  print('HMAC/MD5 => ${md5.hmac.by(pw).string(text)}');
  print('HMAC/SHA1 => ${sha1.hmac.byString(text)}');
  print('HMAC/SHA256 => ${sha256.hmac.byString(key).string(text)}');
  print('HMAC/SHA3-256 => ${HMAC(sha3_256).by(pw).string(text)}');
  print("HMAC/BLAKE2b-256 => ${blake2b512.hmac.by(pw).string(text)}");
  print("BLAKE-2b-MAC/256 => ${blake2b256.mac.by(pw).string(text)}");
  print("BLAKE-2b-MAC/224 => ${Blake2b(28).mac.by(pw).string(text)}");
  print('');

  // Examples of OTP generation
  int nw = DateTime.now().millisecondsSinceEpoch ~/ 30000;
  var counter = fromHex(nw.toRadixString(16).padLeft(16, '0'));
  print('TOTP[time=$nw] => ${TOTP(iv).value()}');
  print('HOTP[counter=$nw] => ${HOTP(iv, counter: counter).value()}');
  print('');
}

Key Generation Example

import 'package:hashlib/hashlib.dart';

void main() {
  final key = "password";
  final salt = "some salt";
  print("key => $key");
  print("salt => $salt");
  print('');

  final pw = key.codeUnits;
  final iv = salt.codeUnits;

  // Examples of Argon2 key derivation
  final argon2Test = Argon2Security.test;
  print("[Argon2i] => ${argon2i(pw, iv, security: argon2Test)}");
  print("[Argon2d] => ${argon2d(pw, iv, security: argon2Test)}");
  print("[Argon2id] => ${argon2id(pw, iv, security: argon2Test)}");

  // Examples of scrypt key derivation
  final scryptLittle = ScryptSecurity.little;
  print("[scrypt] => ${scrypt(pw, iv, security: scryptLittle, dklen: 24)}");
  print('');

  // Examples of bcrypt key derivation
  final bcryptLittle = BcryptSecurity.little;
  print("[bcrypt] => ${bcrypt(pw, bcryptSalt(security: bcryptLittle))}");
  print('');

  // Examples of PBKDF2 key derivation
  print("SHA256/HMAC/PBKDF2 => ${pbkdf2(pw, iv).hex()}");
  print("BLAKE2b-256/HMAC/PBKDF2 => ${blake2b256.pbkdf2(iv).hex(pw)}");
  print("BLAKE2b-256/MAC/PBKDF2 => ${blake2b256.mac.pbkdf2(iv).hex(pw)}");
  print("SHA1/HMAC/PBKDF2 => ${sha1.pbkdf2(iv, iterations: 100).hex(pw)}");
  print('');
}

Random Example

import 'package:hashlib/codecs.dart';
import 'package:hashlib/random.dart';

void main() {
  print('UUID Generation:');
  print('UUIDv1: ${uuid.v1()}');
  print('UUIDv3: ${uuid.v3()}');
  print('UUIDv4: ${uuid.v4()}');
  print('UUIDv5: ${uuid.v5()}');
  print('UUIDv6: ${uuid.v6()}');
  print('UUIDv7: ${uuid.v7()}');
  print('UUIDv8: ${uuid.v8()}');
  print('');

  print('Random Generation:');
  print(randomNumbers(4));
  print(toHex(randomBytes(16)));
  print(randomString(32, lower: true, whitelist: '_'.codeUnits));
  print('');
}

性能基准测试

hashlib 在性能上表现出色,特别是在处理大文件或大量数据时。以下是一些性能对比:

处理5MB消息(10次迭代)

Algorithms hashlib PointyCastle crypto hash
MD4 1.59 Gbps 836 Mbps (1.9x slow) - -
MD5 1.42 Gbps 728 Mbps (1.95x slow) 1.15 Gbps (1.23x slow) 617 Mbps (2.3x slow)

处理1KB消息(5000次迭代)

Algorithms hashlib PointyCastle crypto hash
MD4 1.51 Gbps 795 Mbps (1.9x slow) - -
MD5 1.34 Gbps 684 Mbps (1.96x slow) 1.08 Gbps (1.24x slow) 804 Mbps (1.67x slow)

处理10B消息(100000次迭代)

Algorithms hashlib PointyCastle crypto hash
MD4 261 Mbps 138 Mbps (1.89x slow) - -
MD5 242 Mbps 118 Mbps (2.05x slow) 125 Mbps (1.94x slow) 66.64 Mbps (3.63x slow)

结论

hashlib 是一个功能强大且高效的哈希计算库,适用于各种哈希算法和密钥派生需求。无论是开发加密应用还是需要高性能的哈希计算,hashlib 都是一个值得信赖的选择。


更多关于Flutter哈希计算插件hashlib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter哈希计算插件hashlib的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter中使用hashlib插件进行哈希计算的示例代码。hashlib插件在Flutter中并不直接存在,但我们可以使用类似功能的Dart包,如crypto包,来实现哈希计算。

首先,确保你的Flutter项目中已经添加了crypto包。你可以在pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  crypto: ^3.0.1  # 请检查最新版本号

然后,运行flutter pub get来安装依赖。

接下来,是一个使用crypto包进行哈希计算的示例代码:

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hash Calculation Example'),
        ),
        body: Center(
          child: HashCalculationExample(),
        ),
      ),
    );
  }
}

class HashCalculationExample extends StatefulWidget {
  @override
  _HashCalculationExampleState createState() => _HashCalculationExampleState();
}

class _HashCalculationExampleState extends State<HashCalculationExample> {
  final TextEditingController _controller = TextEditingController();
  String _hashResult = '';

  void _calculateHash() {
    setState(() {
      String input = _controller.text;
      List<int> inputBytes = utf8.encode(input);
      Digest digest = sha256.convert(inputBytes);
      _hashResult = digest.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        TextField(
          controller: _controller,
          decoration: InputDecoration(
            labelText: 'Enter text to hash',
          ),
          maxLines: 4,
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: _calculateHash,
          child: Text('Calculate SHA-256 Hash'),
        ),
        SizedBox(height: 20),
        Text(
          'Hash Result: $_hashResult',
          style: TextStyle(fontSize: 18),
        ),
      ],
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个文本字段用于输入要哈希的文本,一个按钮用于触发哈希计算,以及一个文本组件用于显示计算出的哈希值。

  1. 用户输入的文本通过TextEditingController进行管理。
  2. 当用户点击按钮时,_calculateHash方法被调用。
  3. 输入的文本被转换为UTF-8编码的字节列表。
  4. 使用sha256.convert方法对字节列表进行SHA-256哈希计算。
  5. 计算出的哈希值(以十六进制字符串形式)被显示在屏幕上。

你可以根据需要修改这个示例,例如使用不同的哈希算法(如MD5),只需替换sha256md5即可:

Digest digest = md5.convert(inputBytes);

希望这个示例对你有所帮助!

回到顶部