From ec2e83672afa983237c5caf1d65b06ecc7085b43 Mon Sep 17 00:00:00 2001 From: Aleksey Kulikov Date: Sat, 10 Jan 2026 15:30:00 +0300 Subject: [PATCH] feat(cryptographic): add `apiKey` API method --- lib/src/cryptographic.dart | 25 ++++++++++++++++++++++ test/src/cryptographic_test.dart | 36 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/lib/src/cryptographic.dart b/lib/src/cryptographic.dart index 3d6b455..6d70851 100644 --- a/lib/src/cryptographic.dart +++ b/lib/src/cryptographic.dart @@ -141,4 +141,29 @@ class Cryptographic { return '$header64.$payload64.$signature'; } + + /// Returns API key. + /// + /// [prefix] is optional prefix string (e.g. `sk_`, `pk_`, `api_`). + /// Default is no prefix. + /// + /// [length] is optiontal legnth of the random part (default is 32). + /// + /// [asHex] determines whether returned string should be in hex or base64 + /// (default is hex). + /// + /// Example: + /// ```dart + /// Cryptographic().apiKey(); // "f59e6e027fd23b6721cfa79eb28f58ae" + /// Cryptographic().apiKey(prefix: 'sk_'); // "sk_e95cabd07b0ac9222799ecd4937e6137" + /// Cryptographic().apiKey(prefix: 'pk_', length: 48, asHex: false); // "pk_F7gwa47ywr3yi6UDG-El4sqNUCN_maLAcjZY5omAONoa2WBR" + /// ``` + String apiKey({String prefix = '', int length = 32, bool asHex = true}) { + final key = asHex + ? tokenHex(entropy: length ~/ 2) + : tokenUrlSafe( + entropy: length, + ).replaceAll('=', '').substring(0, length); + return '$prefix$key'; + } } diff --git a/test/src/cryptographic_test.dart b/test/src/cryptographic_test.dart index 44d1e3b..bf0ee2a 100644 --- a/test/src/cryptographic_test.dart +++ b/test/src/cryptographic_test.dart @@ -156,5 +156,41 @@ void main() { ); } }); + + test('returns api key with default params', () { + final result = crypto.apiKey(); + expect(result.length, equals(32)); + expect(seededCrypto.apiKey(), equals(seededCrypto.apiKey())); + }); + + test('returns api key with provided params', () { + const params = [ + // [prefix, length, asHex, expectedMinLength] + ('', 32, true, 32), + ('sk_', 32, true, 35), + ('pk_', 32, true, 35), + ('api_', 32, true, 36), + ('', 64, true, 64), + ('test_', 16, true, 21), + ('', 32, false, 32), + ('sk_', 32, false, 35), + ('pk_', 48, false, 51), + ]; + + for (final (prefix, length, asHex, expectedMinLength) in params) { + final result = crypto.apiKey( + prefix: prefix, + length: length, + asHex: asHex, + ); + expect(result.length, equals(expectedMinLength)); + expect( + seededCrypto.apiKey(prefix: prefix, length: length, asHex: asHex), + equals( + seededCrypto.apiKey(prefix: prefix, length: length, asHex: asHex), + ), + ); + } + }); }); }