| 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) |
| 20 |
(gnutls)) |
| 21 |
|
| 22 |
(define (base64->base64-url str) |
| 23 |
;; Replace '+' with '-', '/' with '_', and remove the '=' padding |
| 24 |
;; characters. |
| 25 |
(string-filter |
| 26 |
(lambda (c) |
| 27 |
(not (eqv? c #\=))) |
| 28 |
(string-map |
| 29 |
(lambda (c) |
| 30 |
(case c |
| 31 |
((#\+) #\-) |
| 32 |
((#\/) #\_) |
| 33 |
(else c))) |
| 34 |
str))) |
| 35 |
|
| 36 |
(define (base64-url->base64 str) |
| 37 |
;; Replace '-' with '+', '_' with '/', and add padding characters. |
| 38 |
(string-append |
| 39 |
(string-map |
| 40 |
(lambda (c) |
| 41 |
(case c |
| 42 |
((#\-) #\+) |
| 43 |
((#\_) #\/) |
| 44 |
(else c))) |
| 45 |
str) |
| 46 |
(case (remainder (string-length str) 4) |
| 47 |
((2) "==") |
| 48 |
((3) "=") |
| 49 |
(else "")))) |
| 50 |
|
| 51 |
(define data |
| 52 |
(string->utf8 "~~ Hello, world! ~~")) |
| 53 |
|
| 54 |
(define encoded |
| 55 |
(base64->base64-url (base64-encode data))) |
| 56 |
|
| 57 |
(define decoded |
| 58 |
(base64-decode (base64-url->base64 encoded))) |
| 59 |
|
| 60 |
(format #t "The base64-url encoding is: ~s\n" |
| 61 |
encoded) |
| 62 |
|
| 63 |
(format #t "Decoding it back gives: ~s\n" |
| 64 |
(utf8->string decoded)) |