Created
May 5, 2024 13:07
-
-
Save HamdaanAliQuatil/bd32945af3091ff7ba72071386ff4de7 to your computer and use it in GitHub Desktop.
Example code for webcrypto.hmac.dart
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 'package:webcrypto/webcrypto.dart'; | |
import 'dart:convert'; | |
Future<void> main() async { | |
// Generate a new key using SHA-256 and an optional length parameter. | |
final key = await HmacSecretKey.generateKey(Hash.sha256, length: 256); | |
// Sign the message. | |
final signature = await key.signBytes(utf8.encode('Hello World!')); | |
// Verify the signature. | |
final verified = await key.verifyBytes(signature, utf8.encode('Hello World!')); | |
assert(verified == true, 'Signature should be valid'); | |
// Sign a stream of data. | |
final signatureStream = await key.signStream(Stream.fromIterable([ | |
utf8.encode('Hello, '), | |
utf8.encode('World!'), | |
])); | |
// Verify the signature. | |
final verifiedStream = await key.verifyStream(signatureStream, Stream.fromIterable([ | |
utf8.encode('Hello, '), | |
utf8.encode('World!'), | |
])); | |
assert(verifiedStream == true, 'Signature should be valid'); | |
// Export the key as raw bytes. | |
final rawKey = await key.exportRawKey(); | |
// Export the key as a JSON Web Key. | |
final jwk = await key.exportJsonWebKey(); | |
print('Signature: $signature'); | |
print('Signature verified: $verified'); | |
print('Signature Stream: $signatureStream'); | |
print('Signature Stream verified: $verifiedStream'); | |
print('Raw key: $rawKey'); | |
print('JSON Web Key: $jwk'); | |
} |
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
Signature: [88, 74, 54, 182, 155, 248, 154, 227, 81, 159, 198, 185, 54, 137, 100, 88, 92, 209, 232, 134, 16, 11, 244, 22, 117, 77, 47, 124, 219, 94, 91, 149] | |
Signature verified: true | |
Signature Stream: [199, 161, 4, 221, 183, 159, 228, 12, 38, 131, 48, 86, 74, 199, 7, 233, 145, 16, 108, 181, 166, 8, 206, 8, 143, 97, 218, 151, 70, 57, 211, 194] | |
Signature Stream verified: true | |
Raw key: [102, 85, 5, 77, 3, 243, 191, 43, 174, 88, 169, 154, 216, 5, 245, 54, 113, 51, 166, 118, 215, 204, 220, 180, 140, 164, 95, 143, 212, 70, 210, 135] | |
JSON Web Key: {kty: oct, use: sig, alg: HS256, k: ZlUFTQPzvyuuWKma2AX1NnEzpnbXzNy0jKRfj9RG0oc} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment