Debian Codegraph @

guile/examples/aead-encrypt-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 (format #t "What is the secret?\n")
25
26 (let ((secret (read-line)))
27 (set! secret
28 (string->utf8 secret))
29 (unless (equal? (bytevector-length secret)
30 (cipher-key-size cipher/aes-256-gcm))
31 (error "incorrect key length"))
32 (format #t "Which file do you want to encrypt?\n")
33 (let ((file-name (read-line)))
34 ;; Create a new state that will be reused when new bytes are
35 ;; available.
36 (let ((cipher (make-aead-cipher cipher/aes-256-gcm secret)))
37 (call-with-output-file (string-append file-name ".encrypted~")
38 (lambda (out)
39 (call-with-input-file file-name
40 (lambda (in)
41 ;; Read raw bytes from the file.
42 (let do-encrypt ()
43 (let ((next (get-bytevector-some in)))
44 (unless (eof-object? next)
45 (let ((encrypted
46 (aead-cipher-encrypt
47 cipher
48 ;; Do not reuse the same nonce twice. The nonce
49 ;; size is constrained; for aes256/GCM, this is 12
50 ;; bytes.
51 (string->utf8 "12 randbytes")
52 (string->utf8 "Additional secret data")
53 0
54 next)))
55 (put-bytevector out encrypted)
56 (do-encrypt))))))
57 #:binary #t))
58 #:binary #t))
59 (rename-file (string-append file-name ".encrypted~")
60 (string-append file-name ".encrypted"))))