Debian Codegraph @

guile/examples/hmac-example-3.scm

raw
1 ;;; GnuTLS --- Guile bindings for GnuTLS.
2 ;;; Copyright (C) 2023-2025 Free Software Foundation, Inc.
3 ;;;
4 ;;; This file is part of Guile-GnuTLS.
5 ;;;
6 ;;; This library is free software; you can redistribute it and/or
7 ;;; modify it under the terms of the GNU Lesser General Public
8 ;;; License as published by the Free Software Foundation; either
9 ;;; version 2.1 of the License, or (at your option) any later version.
10 ;;;
11 ;;; This library is distributed in the hope that it will be useful,
12 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;;; Lesser General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU Lesser General Public
17 ;;; License along with this library; if not, see <https://www.gnu.org/licenses/>.
18
19 (use-modules (rnrs bytevectors) (gnutls))
20
21 (when (defined? 'hmac-copy)
22
23 (let ((hash-with-prefix
24 (lambda (secret prefix)
25 ;; Return a hasher of a string as a 1-argument function,
26 ;; by first adding a prefix to it.
27 (let ((tag (make-prompt-tag)))
28 (call-with-prompt
29 tag
30 (lambda ()
31 (let ((state (make-hmac mac/sha256 secret)))
32 (hmac! state prefix)
33 (let ((line (abort-to-prompt tag)))
34 ;; The flow may reenter multiple times here, so
35 ;; we have to copy the hmac state.
36 (let ((copy (hmac-copy state)))
37 (hmac! copy line)
38 (hmac-output copy)))))
39 (lambda (k) k))))))
40
41 ;; So if "Prefix " is the prefix, it will be hashed only once.
42 (let ((expected-output-1
43 (hmac-direct mac/sha256
44 (string->utf8 "secret!")
45 (string->utf8 "Prefix and then some")))
46 (expected-output-2
47 (hmac-direct mac/sha256
48 (string->utf8 "secret!")
49 (string->utf8 "Prefix and other data"))))
50 ;; hasher is a 1-argument function that computes the hash of
51 ;; "Prefix " + its argument (as bytevectors), but reuses the
52 ;; state it has after hashing "Prefix ".
53 (let ((hasher (hash-with-prefix (string->utf8 "secret!")
54 (string->utf8 "Prefix "))))
55 (let ((output-1 (hasher (string->utf8 "and then some")))
56 (output-2 (hasher (string->utf8 "and other data"))))
57 (unless (and (equal? output-1 expected-output-1)
58 (equal? output-2 expected-output-2))
59 (error "This cannot happen.")))))))