Created
October 17, 2024 03:52
-
-
Save sigmapie8/6208c567f0365b6c783055768e6e579d to your computer and use it in GitHub Desktop.
How to use bloom filters for constant time password blacklisting
This file contains hidden or 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:convert'; | |
| import 'dart:io'; | |
| import 'package:dart_bloom_filter/dart_bloom_filter.dart'; | |
| import 'package:path/path.dart' as path; | |
| // compile step, required only once | |
| /// [createBloomy] allows you to create and serialize your bloom filter | |
| /// to be further used anywhere | |
| void createBloomy() { | |
| final bloomFilter = BloomFilter.murmur(10000, 0.001, 12345); | |
| // get the content | |
| final passwordFileContent = | |
| File(path.canonicalize("./assets/10k-worst-passwords.txt")) | |
| .readAsLinesSync(); | |
| // populate the filter | |
| for (String password in passwordFileContent) { | |
| bloomFilter.add(item: password); | |
| } | |
| // serialize the filter | |
| final filterFile = File("./bloom-filter"); | |
| filterFile.writeAsStringSync(jsonEncode(bloomFilter.toJson())); | |
| } | |
| BloomFilter getBloomy() { | |
| // de-serializing bloom filter | |
| // NOTE: please don't use sync operations for very big files | |
| final bloomFilterContent = File("./bloom-filter").readAsStringSync(); | |
| final passwordFilter = BloomFilter.fromJson(jsonDecode(bloomFilterContent)); | |
| return passwordFilter; | |
| } | |
| bool checkPassword({required String password, required BloomFilter filter}) { | |
| return filter.contains(item: password); | |
| } | |
| void main() { | |
| final passwordFilter = getBloomy(); | |
| if (passwordFilter.contains(item: "password")) { | |
| print( | |
| "This password can be easily guessed, please use a different password"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment