diff --git a/lisp/gnus/gnus-util.el b/lisp/gnus/gnus-util.el index aa9f137e20..7e8dcaa47c 100644 --- a/lisp/gnus/gnus-util.el +++ b/lisp/gnus/gnus-util.el @@ -1343,6 +1343,58 @@ gnus-url-unhex-string (setq tmp (concat tmp str)) tmp)) +(defun gnus-base64-repad (str &optional reject-newlines line-length) + "Take a base 64-encoded string and return it padded correctly, +regardless of what padding the input string alread had. + +If any combination of CR and LF characters are present and +REJECT-NEWLINES is nil remove them, otherwise raise an error. If +LINE-LENGTH is set and the string (or any line in the string if +REJECT-NEWLINES is nil) is longer than that number, raise an +error. Common line length for input characters are 76 plus CRLF +(RFC 2045 MIME), 64 plus CRLF (RFC 1421 PEM), and 1000 including +CRLF (RFC 5321 SMTP). +" + ;;; RFC 4648 specifies that: + ;;; - three 8-bit inputs make up a 24-bit group + ;;; - the 24-bit group is broken up into four 6-bit values + ;;; - each 6-bit value is mapped to one character of the base 64 alphabet + ;;; - if the final 24-bit quantum is filled with only 8 bits the output + ;;; will be two base 64 characters followed by two "=" padding characters + ;;; - if the final 24-bit quantum is filled with only 16 bits the output + ;;; will be three base 64 character followed by one "=" padding character + ;;; + ;;; RFC 4648 section 3 considerations: + ;;; - if reject-newlines is nil (default), concatenate multi-line + ;;; input (3.1, 3.3) + ;;; - if line-length is set, error on input exceeding the limit (3.1) + ;;; - reject characters outside base encoding (3.3, also section 12) + + (let ((splitstr (split-string str "[\r\n]" t))) + (progn + (if (and reject-newlines (> (length splitstr) 1)) + (error "Invalid Base64 string")) + (dolist (substr splitstr) + (if (and line-length (> (length substr) line-length)) + (error "Base64 string exceeds line-length")) + (if (string-match "[^A-Za-z0-9+/=]" substr) + (error "Invalid Base64 string"))) + (let* ((str (string-join splitstr)) + (len (length str)) + (padding nil)) + (if (string-match "=" str) + (setq len (match-beginning 0))) + (progn (setq padding + (/ + (- 24 + (pcase (mod (* len 6) 24) + (`0 24) + (n n))) + 6)) + (concat + (substring str 0 len) + (make-string padding ?=))))))) + (defun gnus-make-predicate (spec) "Transform SPEC into a function that can be called. SPEC is a predicate specifier that contains stuff like `or', `and',