1 ;;; hmac-def.el --- A macro for defining HMAC functions.
3 ;; Copyright (C) 1999, 2001, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Shuhei KOBAYASHI <shuhei@aqua.ocn.ne.jp>
6 ;; Keywords: HMAC, RFC 2104
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 <http://www.gnu.org/licenses/>.
25 ;; This program is implemented from RFC 2104,
26 ;; "HMAC: Keyed-Hashing for Message Authentication".
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
)
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))
50 ;; if `key' is longer than the block size, apply hash function
51 ;; to `key' and use the result as a real `key'.
56 (aset key-xor-ipad pos
(logxor (aref key pos
) ?
\x36))
57 (aset key-xor-opad pos
(logxor (aref key pos
) ?
\x5C))
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
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
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
)))
78 (fillarray key-xor-ipad
0)
79 (fillarray key-xor-opad
0)))))
83 ;; arch-tag: 645adcef-b835-4900-a10a-11f636c982b9
84 ;;; hmac-def.el ends here