Debian Codegraph @

guile/examples/low-level-cipher-example.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 (ice-9 rdelim)
20 (ice-9 binary-ports)
21 (rnrs bytevectors)
22 (gnutls))
23
24 ;; To define a symmetric encryption cipher context, you need an algorithm, a
25 ;; key, and an initialization vector.
26
27 (define algorithm cipher/aes-128-cbc)
28
29 (define cipher
30 (let ((initialisation-vector
31 (string->utf8 "Initialisation.."))
32 (key
33 (string->utf8 "The 16-byte key.")))
34 (unless (eqv? (bytevector-length initialisation-vector)
35 (cipher-iv-size algorithm))
36 (error "Incorrect initialization vector size."))
37 (unless (eqv? (bytevector-length key)
38 (cipher-key-size algorithm))
39 (error "Incorrect key size."))
40 (make-cipher algorithm key initialisation-vector)))
41
42 ;; The context may be used to encrypt and decrypt data, if the data spans an
43 ;; integer number of blocks.
44
45 (define block-size
46 (cipher-block-size (cipher-algorithm cipher)))
47
48 (define data
49 (string->utf8 "The data to encrypt must be a bytevector \
50 whose length must be a multiple of the block size. If you \
51 want to use the low-level cipher API, you must manage the \
52 data padding yourself, and know the message length."))
53
54 (define encrypted
55 (cipher-encrypt cipher data))
56
57 (define decrypted
58 (cipher-decrypt cipher encrypted))
59
60 (unless (equal? data decrypted)
61 (error "data decryption failed."))