base64.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. ;; -*- mode: scheme; coding: utf-8 -*-
  2. ;;
  3. ;; This module was renamed from (weinholt text base64 (1 0 20100612)) to
  4. ;; (guix base64) by Nikita Karetnikov <nikita@karetnikov.org> on
  5. ;; February 12, 2014. It was later renamed to (gcrypt base64) by
  6. ;; Christopher Allan Webber <cwebber@dustycloud.org> on May 20, 2017.
  7. ;;
  8. ;; Some optimizations made by Ludovic Courtès <ludo@gnu.org>, 2015.
  9. ;; Turned into a Guile module (instead of R6RS).
  10. ;;
  11. ;; This program is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;;
  16. ;; This program is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;;
  21. ;; You should have received a copy of the GNU General Public License
  22. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. ;;
  24. ;; This file incorporates work covered by the following copyright and
  25. ;; permission notice:
  26. ;;
  27. ;; Copyright © 2009, 2010 Göran Weinholt <goran@weinholt.se>
  28. ;;
  29. ;; Permission is hereby granted, free of charge, to any person obtaining a
  30. ;; copy of this software and associated documentation files (the "Software"),
  31. ;; to deal in the Software without restriction, including without limitation
  32. ;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
  33. ;; and/or sell copies of the Software, and to permit persons to whom the
  34. ;; Software is furnished to do so, subject to the following conditions:
  35. ;;
  36. ;; The above copyright notice and this permission notice shall be included in
  37. ;; all copies or substantial portions of the Software.
  38. ;;
  39. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  40. ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  41. ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  42. ;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  43. ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  44. ;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  45. ;; DEALINGS IN THE SOFTWARE.
  46. ;; RFC 4648 Base-N Encodings
  47. (define-module (gcrypt base64)
  48. #:export (base64-encode
  49. base64-decode
  50. base64-alphabet
  51. base64url-alphabet
  52. get-delimited-base64
  53. put-delimited-base64)
  54. #:use-module (srfi srfi-11)
  55. #:use-module (srfi srfi-60)
  56. #:use-module (rnrs bytevectors)
  57. #:use-module (rnrs io ports))
  58. (define-syntax define-alias
  59. (syntax-rules ()
  60. ((_ new old)
  61. (define-syntax new (identifier-syntax old)))))
  62. ;; Force the use of Guile's own primitives to avoid the overhead of its 'fx'
  63. ;; procedures.
  64. (define-alias fxbit-field bit-field)
  65. (define-alias fxarithmetic-shift ash)
  66. (define-alias fxarithmetic-shift-left ash)
  67. (define-alias fxand logand)
  68. (define-alias fxior logior)
  69. (define-alias fxxor logxor)
  70. (define-alias fx=? =)
  71. (define-alias fx+ +)
  72. (define-alias mod modulo)
  73. (define-syntax-rule (assert exp)
  74. (unless exp
  75. (throw 'assertion-failure 'exp)))
  76. (define base64-alphabet
  77. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
  78. (define base64url-alphabet
  79. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
  80. (define base64-encode
  81. (case-lambda
  82. ;; Simple interface. Returns a string containing the canonical
  83. ;; base64 representation of the given bytevector.
  84. ((bv)
  85. (base64-encode bv 0 (bytevector-length bv) #f #f base64-alphabet #f))
  86. ((bv start)
  87. (base64-encode bv start (bytevector-length bv) #f #f base64-alphabet #f))
  88. ((bv start end)
  89. (base64-encode bv start end #f #f base64-alphabet #f))
  90. ((bv start end line-length)
  91. (base64-encode bv start end line-length #f base64-alphabet #f))
  92. ((bv start end line-length no-padding)
  93. (base64-encode bv start end line-length no-padding base64-alphabet #f))
  94. ((bv start end line-length no-padding alphabet)
  95. (base64-encode bv start end line-length no-padding alphabet #f))
  96. ;; Base64 encodes the bytes [start,end[ in the given bytevector.
  97. ;; Lines are limited to line-length characters (unless #f),
  98. ;; which must be a multiple of four. To omit the padding
  99. ;; characters (#\=) set no-padding to a true value. If port is
  100. ;; #f, returns a string.
  101. ((bv start end line-length no-padding alphabet port)
  102. (assert (or (not line-length) (zero? (mod line-length 4))))
  103. (let-values (((p extract) (if port
  104. (values port (lambda () (values)))
  105. (open-string-output-port))))
  106. (letrec ((put (if line-length
  107. (let ((chars 0))
  108. (lambda (p c)
  109. (when (fx=? chars line-length)
  110. (set! chars 0)
  111. (put-char p #\linefeed))
  112. (set! chars (fx+ chars 1))
  113. (put-char p c)))
  114. put-char)))
  115. (let lp ((i start))
  116. (cond ((= i end))
  117. ((<= (+ i 3) end)
  118. (let ((x (bytevector-uint-ref bv i (endianness big) 3)))
  119. (put p (string-ref alphabet (fxbit-field x 18 24)))
  120. (put p (string-ref alphabet (fxbit-field x 12 18)))
  121. (put p (string-ref alphabet (fxbit-field x 6 12)))
  122. (put p (string-ref alphabet (fxbit-field x 0 6)))
  123. (lp (+ i 3))))
  124. ((<= (+ i 2) end)
  125. (let ((x (fxarithmetic-shift-left (bytevector-u16-ref bv i (endianness big)) 8)))
  126. (put p (string-ref alphabet (fxbit-field x 18 24)))
  127. (put p (string-ref alphabet (fxbit-field x 12 18)))
  128. (put p (string-ref alphabet (fxbit-field x 6 12)))
  129. (unless no-padding
  130. (put p #\=))))
  131. (else
  132. (let ((x (fxarithmetic-shift-left (bytevector-u8-ref bv i) 16)))
  133. (put p (string-ref alphabet (fxbit-field x 18 24)))
  134. (put p (string-ref alphabet (fxbit-field x 12 18)))
  135. (unless no-padding
  136. (put p #\=)
  137. (put p #\=)))))))
  138. (extract)))))
  139. ;; Decodes a base64 string. The string must contain only pure
  140. ;; unpadded base64 data.
  141. (define base64-decode
  142. (case-lambda
  143. ((str)
  144. (base64-decode str base64-alphabet #f))
  145. ((str alphabet)
  146. (base64-decode str alphabet #f))
  147. ((str alphabet port)
  148. (unless (zero? (mod (string-length str) 4))
  149. (error 'base64-decode
  150. "input string must be a multiple of four characters"))
  151. (let-values (((p extract) (if port
  152. (values port (lambda () (values)))
  153. (open-bytevector-output-port))))
  154. (do ((i 0 (+ i 4)))
  155. ((= i (string-length str))
  156. (extract))
  157. (let ((c1 (string-ref str i))
  158. (c2 (string-ref str (+ i 1)))
  159. (c3 (string-ref str (+ i 2)))
  160. (c4 (string-ref str (+ i 3))))
  161. ;; TODO: be more clever than string-index
  162. (let ((i1 (string-index alphabet c1))
  163. (i2 (string-index alphabet c2))
  164. (i3 (string-index alphabet c3))
  165. (i4 (string-index alphabet c4)))
  166. (cond ((and i1 i2 i3 i4)
  167. (let ((x (fxior (fxarithmetic-shift-left i1 18)
  168. (fxarithmetic-shift-left i2 12)
  169. (fxarithmetic-shift-left i3 6)
  170. i4)))
  171. (put-u8 p (fxbit-field x 16 24))
  172. (put-u8 p (fxbit-field x 8 16))
  173. (put-u8 p (fxbit-field x 0 8))))
  174. ((and i1 i2 i3 (char=? c4 #\=)
  175. (= i (- (string-length str) 4)))
  176. (let ((x (fxior (fxarithmetic-shift-left i1 18)
  177. (fxarithmetic-shift-left i2 12)
  178. (fxarithmetic-shift-left i3 6))))
  179. (put-u8 p (fxbit-field x 16 24))
  180. (put-u8 p (fxbit-field x 8 16))))
  181. ((and i1 i2 (char=? c3 #\=) (char=? c4 #\=)
  182. (= i (- (string-length str) 4)))
  183. (let ((x (fxior (fxarithmetic-shift-left i1 18)
  184. (fxarithmetic-shift-left i2 12))))
  185. (put-u8 p (fxbit-field x 16 24))))
  186. (else
  187. (error 'base64-decode "invalid input"
  188. (list c1 c2 c3 c4)))))))))))
  189. (define (get-line-comp f port)
  190. (if (port-eof? port)
  191. (eof-object)
  192. (f (get-line port))))
  193. ;; Reads the common -----BEGIN/END type----- delimited format from
  194. ;; the given port. Returns two values: a string with the type and a
  195. ;; bytevector containing the base64 decoded data. The second value
  196. ;; is the eof object if there is an eof before the BEGIN delimiter.
  197. (define (get-delimited-base64 port)
  198. (define (get-first-data-line port)
  199. ;; Some MIME data has header fields in the same format as mail
  200. ;; or http. These are ignored.
  201. (let ((line (get-line-comp string-trim-both port)))
  202. (cond ((eof-object? line) line)
  203. ((string-index line #\:)
  204. (let lp () ;read until empty line
  205. (let ((line (get-line-comp string-trim-both port)))
  206. (if (string=? line "")
  207. (get-line-comp string-trim-both port)
  208. (lp)))))
  209. (else line))))
  210. (let ((line (get-line-comp string-trim-both port)))
  211. (cond ((eof-object? line)
  212. (values "" (eof-object)))
  213. ((string=? line "")
  214. (get-delimited-base64 port))
  215. ((and (string-prefix? "-----BEGIN " line)
  216. (string-suffix? "-----" line))
  217. (let* ((type (substring line 11 (- (string-length line) 5)))
  218. (endline (string-append "-----END " type "-----")))
  219. (let-values (((outp extract) (open-bytevector-output-port)))
  220. (let lp ((line (get-first-data-line port)))
  221. (cond ((eof-object? line)
  222. (error 'get-delimited-base64
  223. "unexpected end of file"))
  224. ((string-prefix? "-" line)
  225. (unless (string=? line endline)
  226. (error 'get-delimited-base64
  227. "bad end delimiter" type line))
  228. (values type (extract)))
  229. (else
  230. (unless (and (= (string-length line) 5)
  231. (string-prefix? "=" line)) ;Skip Radix-64 checksum
  232. (base64-decode line base64-alphabet outp))
  233. (lp (get-line-comp string-trim-both port))))))))
  234. (else ;skip garbage (like in openssl x509 -in foo -text output).
  235. (get-delimited-base64 port)))))
  236. (define put-delimited-base64
  237. (case-lambda
  238. ((port type bv line-length)
  239. (display (string-append "-----BEGIN " type "-----\n") port)
  240. (base64-encode bv 0 (bytevector-length bv)
  241. line-length #f base64-alphabet port)
  242. (display (string-append "\n-----END " type "-----\n") port))
  243. ((port type bv)
  244. (put-delimited-base64 port type bv 76))))