Spelling fixes
[emacs.git] / lisp / net / hmac-def.el
blob24246af02e7dab7ba1077df293a1a36b8c537c1b
1 ;;; hmac-def.el --- A macro for defining HMAC functions.
3 ;; Copyright (C) 1999, 2001, 2007-2017 Free Software Foundation, Inc.
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
6 ;; Keywords: HMAC, RFC2104
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This program is implemented from RFC2104,
26 ;; "HMAC: Keyed-Hashing for Message Authentication".
28 ;;; Code:
30 (defmacro define-hmac-function (name H B L &optional bit)
31 "Define a function NAME(TEXT KEY) which computes HMAC with function H.
33 HMAC function is H(KEY XOR opad, H(KEY XOR ipad, TEXT)):
35 H is a cryptographic hash function, such as SHA1 and MD5, which takes
36 a string and return a digest of it (in binary form).
37 B is a byte-length of a block size of H. (B=64 for both SHA1 and MD5.)
38 L is a byte-length of hash outputs. (L=16 for MD5, L=20 for SHA1.)
39 If BIT is non-nil, truncate output to specified bits."
40 `(defun ,name (text key)
41 ,(concat "Compute "
42 (upcase (symbol-name name))
43 " over TEXT with KEY.")
44 (let ((key-xor-ipad (make-string ,B ?\x36))
45 (key-xor-opad (make-string ,B ?\x5C))
46 (len (length key))
47 (pos 0))
48 (unwind-protect
49 (progn
50 ;; if `key' is longer than the block size, apply hash function
51 ;; to `key' and use the result as a real `key'.
52 (if (> len ,B)
53 (setq key (,H key)
54 len ,L))
55 (while (< pos len)
56 (aset key-xor-ipad pos (logxor (aref key pos) ?\x36))
57 (aset key-xor-opad pos (logxor (aref key pos) ?\x5C))
58 (setq pos (1+ pos)))
59 (setq key-xor-ipad (unwind-protect
60 (concat key-xor-ipad text)
61 (fillarray key-xor-ipad 0))
62 key-xor-ipad (unwind-protect
63 (,H key-xor-ipad)
64 (fillarray key-xor-ipad 0))
65 key-xor-opad (unwind-protect
66 (concat key-xor-opad key-xor-ipad)
67 (fillarray key-xor-opad 0))
68 key-xor-opad (unwind-protect
69 (,H key-xor-opad)
70 (fillarray key-xor-opad 0)))
71 ;; now `key-xor-opad' contains
72 ;; H(KEY XOR opad, H(KEY XOR ipad, TEXT)).
73 ,(if (and bit (< (/ bit 8) L))
74 `(substring key-xor-opad 0 ,(/ bit 8))
75 ;; return a copy of `key-xor-opad'.
76 `(concat key-xor-opad)))
77 ;; cleanup.
78 (fillarray key-xor-ipad 0)
79 (fillarray key-xor-opad 0)))))
81 (provide 'hmac-def)
83 ;;; hmac-def.el ends here