├── .github └── workflows │ └── workflow.yaml ├── .gitignore ├── LICENSE ├── README.md ├── cmac.go ├── cmac_test.go └── go.mod /.github/workflows/workflow.yaml: -------------------------------------------------------------------------------- 1 | name: Test and build 2 | 3 | # Controls when the action will run. Triggers the workflow on push or pull request 4 | # events but only for the master branch 5 | on: 6 | push: 7 | branches: 8 | - master 9 | pull_request: 10 | branches: 11 | - master 12 | 13 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 14 | jobs: 15 | # The "build" workflow 16 | build: 17 | # The type of runner that the job will run on 18 | runs-on: ubuntu-latest 19 | 20 | # Steps represent a sequence of tasks that will be executed as part of the job 21 | steps: 22 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 23 | - uses: actions/checkout@v2 24 | 25 | # Setup Go 26 | - name: Setup Go 27 | uses: actions/setup-go@v2 28 | with: 29 | go-version: '1.17.0' # The Go version to download (if necessary) and use. 30 | 31 | # Install all the dependencies 32 | - name: Install dependencies 33 | run: | 34 | go version 35 | go get -u golang.org/x/lint/golint 36 | 37 | # Run build of the application 38 | - name: Run build 39 | run: go build . 40 | 41 | # Run vet & lint on the code 42 | - name: Run vet & lint 43 | run: | 44 | go vet . 45 | golint . 46 | 47 | # Run testing on the code 48 | - name: Run testing 49 | #run: cd test && go test -v 50 | run: go test -v 51 | 52 | # Run coverage 53 | - name: Run coverage 54 | run: go test -race -coverprofile=coverage.out -covermode=atomic 55 | 56 | # Upload coverage 57 | - name: Upload coverage to Codecov 58 | run: bash <(curl -s https://codecov.io/bash) 59 | 60 | # Force update go.pkg.dev documentation 61 | - name: Force update go.pkg.dev 62 | run: | 63 | curl https://proxy.golang.org/github.com/${{github.repository}}/@latest 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | c.out -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Christophe Meessen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![GoDoc](https://img.shields.io/badge/go.dev-reference-blue)](https://pkg.go.dev/github.com/chmike/cmac-go) 2 | ![Build](https://github.com/chmike/cmac-go/actions/workflows/workflow.yaml/badge.svg) 3 | [![codecov](https://codecov.io/gh/chmike/cmac-go/branch/master/graph/badge.svg?token=9XNNVJXV1E)](https://codecov.io/gh/chmike/cmac-go) 4 | [![Go Report](https://goreportcard.com/badge/github.com/chmike/cmac-go)](https://goreportcard.com/report/github.com/chmike/cmac-go) 5 | ![Status](https://img.shields.io/badge/status-stable-brightgreen.svg) 6 | ![release](https://img.shields.io/github/release/chmike/cmac-go.svg) 7 | 8 | # Cipher-based Message Authentication Code 9 | 10 | This package implements the Cipher-based Message Authentication Code as 11 | defined in the RFC4493 and NIST special publication 800-38B, "Recommendation 12 | for Block Cipher Modes of Operation: The CMAC Mode for Authentication", May 2005. 13 | 14 | It achieves a security goal similar to that of HMAC, but uses a symmetric key 15 | block cipher like AES. CMAC is appropriate for information systems in which a 16 | block cipher is more readily available than a hash function. 17 | 18 | Like HMAC, CMAC uses a key to sign a message. The receiver verifies the 19 | Massage Authenticating Code by recomputing it using the same key. 20 | 21 | ## Installation 22 | 23 | go get github.com/chmike/cmac-go 24 | 25 | ## Usage example 26 | 27 | ```go 28 | import ( 29 | "crypto/aes" 30 | 31 | "github.com/chmike/cmac-go" 32 | ) 33 | 34 | // Instantiate the cmac hash.Hash. 35 | cm, err := cmac.New(aes.NewCipher, key) 36 | if err != nil { 37 | // ... 38 | } 39 | 40 | // Compute the CMAC of a message. Never returns an error. 41 | // The parameter may be an empty slice or nil. 42 | // Write may be called multiple times. 43 | cm.Write([]byte("some message")) 44 | 45 | // Get the computed MAC. It may be followed by more Writes and sum calls. 46 | mac1 := cm.Sum(nil) 47 | 48 | // Important: use cmac.Equal() instead of bytes.Equal(). 49 | // It doesn't leak timing information. 50 | if !cmac.Equal(mac1, mac2) { 51 | // mac mismatch 52 | } 53 | 54 | // Use Reset to clear the state of the cmac calculator. You may then 55 | // start processing a new message. 56 | cm.Reset() 57 | ``` 58 | -------------------------------------------------------------------------------- /cmac.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package cmac implements the Cipher-based Message Authentication Code as 3 | defined in the RFC4493 and NIST special publication 800-38B, "Recommendation 4 | for Block Cipher Modes of Operation: The CMAC Mode for Authentication", May 2005. 5 | 6 | It achieves a security goal similar to that of HMAC, but uses a symmetric key 7 | block cipher like AES. CMAC is appropriate for information systems in which a 8 | block cipher is more readily available than a hash function. 9 | 10 | Like HMAC, CMAC uses a key to sign a message. The receiver verifies the 11 | Massage Authenticating Code by recomputing it using the same key. 12 | 13 | Receivers should be careful to use Equal to compare MACs in order to avoid 14 | timing side-channels: 15 | 16 | // CheckMAC reports whether messageMAC is a valid HMAC tag for message. 17 | func CheckMAC(message, messageMAC, key []byte) bool { 18 | mac := cmac.New(aes.New, key) 19 | mac.Write(message) 20 | expectedMAC := mac.Sum(nil) 21 | return cmac.Equal(messageMAC, expectedMAC) 22 | } 23 | */ 24 | package cmac 25 | 26 | import ( 27 | "crypto/cipher" 28 | "hash" 29 | ) 30 | 31 | /* CMAC uses mac with no iv to compute the MAC. 32 | 33 | +-----+ +-----+ +-----+ +-----+ +-----+ +---+----+ 34 | | M_1 | | M_2 | | M_n | | M_1 | | M_2 | |M_n|10^i| 35 | +-----+ +-----+ +-----+ +-----+ +-----+ +---+----+ 36 | | | | +--+ | | | +--+ 37 | | +--->(+) +--->(+)<-|K1| | +--->(+) +--->(+)<-|K2| 38 | | | | | | +--+ | | | | | +--+ 39 | +-----+ | +-----+ | +-----+ +-----+ | +-----+ | +-----+ 40 | |AES_K| | |AES_K| | |AES_K| |AES_K| | |AES_K| | |AES_K| 41 | +-----+ | +-----+ | +-----+ +-----+ | +-----+ | +-----+ 42 | | | | | | | | | | | 43 | +-----+ +-----+ | +-----+ +-----+ | 44 | | | 45 | +-----+ +-----+ 46 | | T | | T | 47 | +-----+ +-----+ 48 | 49 | Illustration of the two cases of CMAC computation using the cipher AES. 50 | 51 | The case on the left is when the number of bytes of the message is a multiple 52 | of the block size. The case of the right is when padding bits must be 53 | appended to the last block to get a full block. The padding is the bit 1 54 | followed by as many bit 0 as required. 55 | 56 | K1 and K2 have the size of a block and are computed as follow: 57 | 58 | const_zero = [0, ..., 0, 0] 59 | const_Rb = [0, ..., 0, 0x87] 60 | 61 | Step 1. L := AES-128(K, const_Zero); 62 | Step 2. if MostSignificantBit(L) is equal to 0 63 | then K1 := L << 1; 64 | else K1 := (L << 1) XOR const_Rb; 65 | Step 3. if MostSignificantBit(K1) is equal to 0 66 | then K2 := K1 << 1; 67 | else K2 := (K1 << 1) XOR const_Rb; 68 | */ 69 | 70 | type cmac struct { 71 | blockSize, n int 72 | mac, k1, k2, x []byte 73 | cipher cipher.Block 74 | } 75 | 76 | // NewCipherFunc instantiates a block cipher 77 | type NewCipherFunc func(key []byte) (cipher.Block, error) 78 | 79 | // New returns a new CMAC hash using the given cipher instantiation function and key. 80 | func New(newCipher NewCipherFunc, key []byte) (hash.Hash, error) { 81 | c, err := newCipher(key) 82 | if err != nil { 83 | return nil, err 84 | } 85 | var bs = c.BlockSize() 86 | var cm = new(cmac) 87 | cm.blockSize = bs 88 | b := make([]byte, 4*bs) 89 | cm.mac, cm.k1, cm.k2, cm.x = b[:bs], b[bs:2*bs], b[2*bs:3*bs], b[3*bs:4*bs] 90 | cm.cipher = c 91 | c.Encrypt(cm.k1, cm.k1) 92 | tmp := cm.k1[0] 93 | shiftLeftOneBit(cm.k1, cm.k1) 94 | cm.k1[bs-1] ^= 0x87 & byte(int8(tmp)>>7) // xor with 0x87 when most significant bit of tmp is 1 95 | tmp = cm.k1[0] 96 | shiftLeftOneBit(cm.k2, cm.k1) 97 | cm.k2[bs-1] ^= 0x87 & byte(int8(tmp)>>7) // xor with 0x87 when most significant bit of tmp is 1 98 | return cm, nil 99 | } 100 | 101 | func (c *cmac) Size() int { return c.blockSize } 102 | 103 | func (c *cmac) BlockSize() int { return c.blockSize } 104 | 105 | func shiftLeftOneBit(dst, src []byte) { 106 | var overflow byte 107 | for i := len(src) - 1; i >= 0; i-- { 108 | var tmp = src[i] 109 | dst[i] = (tmp << 1) | overflow 110 | overflow = tmp >> 7 111 | } 112 | } 113 | 114 | // Write accumulates the bytes in m in the cmac computation. 115 | func (c *cmac) Write(m []byte) (n int, err error) { 116 | n = len(m) 117 | if l := c.blockSize - c.n; len(m) > l { 118 | xor(c.x[c.n:], m[:l]) 119 | m = m[l:] 120 | c.cipher.Encrypt(c.x, c.x) 121 | c.n = 0 122 | } 123 | for len(m) > c.blockSize { 124 | xor(c.x, m[:c.blockSize]) 125 | m = m[c.blockSize:] 126 | c.cipher.Encrypt(c.x, c.x) 127 | } 128 | if len(m) > 0 { 129 | xor(c.x[c.n:], m) 130 | c.n += len(m) 131 | } 132 | return 133 | } 134 | 135 | // Sum returns the CMAC appended to m. m may be nil. Write may be called after Sum. 136 | func (c *cmac) Sum(m []byte) []byte { 137 | if c.n == c.blockSize { 138 | copy(c.mac, c.k1) 139 | } else { 140 | copy(c.mac, c.k2) 141 | c.mac[c.n] ^= 0x80 142 | } 143 | xor(c.mac, c.x) 144 | c.cipher.Encrypt(c.mac, c.mac) 145 | return append(m, c.mac...) 146 | } 147 | 148 | // Reset the the CMAC 149 | func (c *cmac) Reset() { 150 | for i := range c.x { 151 | c.x[i] = 0 152 | } 153 | c.n = 0 154 | } 155 | 156 | // xor stores a xor b in a. The length of b must be smaller or equal to a. 157 | func xor(a, b []byte) { 158 | for i, v := range b { 159 | a[i] ^= v 160 | } 161 | } 162 | 163 | // Equal compares two MACs for equality without leaking timing information. 164 | func Equal(mac1, mac2 []byte) bool { 165 | if len(mac1) != len(mac2) { 166 | return false 167 | } 168 | // copied from libsodium 169 | var b byte 170 | for i := range mac1 { 171 | b |= mac1[i] ^ mac2[i] 172 | } 173 | return ((uint16(b)-1)>>8)&1 == 1 174 | } 175 | -------------------------------------------------------------------------------- /cmac_test.go: -------------------------------------------------------------------------------- 1 | package cmac 2 | 3 | import ( 4 | "bytes" 5 | "crypto/aes" 6 | "encoding/hex" 7 | "testing" 8 | ) 9 | 10 | // using test vectors from RFC4493 11 | func TestCMAC(t *testing.T) { 12 | key := "2b7e151628aed2a6abf7158809cf4f3c" 13 | k1 := "fbeed618357133667c85e08f7236a8de" 14 | k2 := "f7ddac306ae266ccf90bc11ee46d513b" 15 | 16 | keyBytes, _ := hex.DecodeString(key) 17 | k1Bytes, _ := hex.DecodeString(k1) 18 | k2Bytes, _ := hex.DecodeString(k2) 19 | 20 | _, err := New(aes.NewCipher, nil) 21 | if err == nil { 22 | t.Fatal("unexpeced nil error") 23 | } 24 | 25 | cm, err := New(aes.NewCipher, keyBytes) 26 | if err != nil { 27 | t.Fatal("unexpected error: ", err) 28 | } 29 | tmp := cm.(*cmac) 30 | if !bytes.Equal(tmp.k1, k1Bytes) { 31 | t.Errorf("k1 mismatch, got \n %+v\nexpected\n %+v", tmp.k1, k1) 32 | } 33 | if !bytes.Equal(tmp.k2, k2Bytes) { 34 | t.Errorf("k2 mismatch, got \n %+v\nexpected\n %+v", tmp.k2, k2) 35 | } 36 | 37 | if !Equal(keyBytes, keyBytes) { 38 | t.Errorf("got equal false, expected true") 39 | } 40 | if Equal(keyBytes, k1Bytes) { 41 | t.Errorf("got equal true, expected false") 42 | } 43 | if Equal(keyBytes, k1Bytes[:5]) { 44 | t.Errorf("got equal true, expected false") 45 | } 46 | 47 | if cm.Size() != len(keyBytes) { 48 | t.Fatalf("expected Size %d, got %d", len(keyBytes), cm.Size()) 49 | } 50 | 51 | if cm.Size() != cm.BlockSize() { 52 | t.Fatalf("expected same Size and BlockSize") 53 | } 54 | 55 | tests := []struct { 56 | msg, mac string 57 | }{ 58 | { 59 | msg: "", 60 | mac: "bb1d6929e95937287fa37d129b756746", 61 | }, 62 | { 63 | msg: "6bc1bee22e409f96e93d7e117393172a", 64 | mac: "070a16b46b4d4144f79bdd9dd04a287c", 65 | }, 66 | { 67 | msg: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411", 68 | mac: "dfa66747de9ae63030ca32611497c827", 69 | }, 70 | { 71 | msg: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 72 | mac: "51f0bebf7e3b9d92fc49741779363cfe", 73 | }, 74 | } 75 | for i, test := range tests { 76 | cm.Reset() 77 | msgBytes, _ := hex.DecodeString(test.msg) 78 | n, err := cm.Write(msgBytes) 79 | if err != nil { 80 | t.Errorf("%2d: unexpected error: %s", i, err) 81 | continue 82 | } 83 | if len(msgBytes) != n { 84 | t.Errorf("%2d: expect len %d, got %d", i, len(msgBytes), n) 85 | continue 86 | } 87 | macBytes, _ := hex.DecodeString(test.mac) 88 | if !Equal(cm.Sum(nil), macBytes) { 89 | t.Errorf("%2d: mac mismatch", i) 90 | } 91 | } 92 | } 93 | 94 | // Other test vectors 95 | // See https://github.com/ircmaxell/PHP-PasswordLib/blob/master/test/Data/Vectors/cmac-aes.sp-800-38b.test-vectors 96 | func TestAESCMAC2(t *testing.T) { 97 | tests := []struct { 98 | key, plain, mac string 99 | }{ 100 | // 0 101 | { 102 | key: "2b7e151628aed2a6abf7158809cf4f3c", 103 | plain: "", 104 | mac: "bb1d6929e95937287fa37d129b756746", 105 | }, 106 | { 107 | key: "2b7e151628aed2a6abf7158809cf4f3c", 108 | plain: "6bc1bee22e409f96e93d7e117393172a", 109 | mac: "070a16b46b4d4144f79bdd9dd04a287c", 110 | }, 111 | { 112 | key: "2b7e151628aed2a6abf7158809cf4f3c", 113 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411", 114 | mac: "dfa66747de9ae63030ca32611497c827", 115 | }, 116 | { 117 | key: "2b7e151628aed2a6abf7158809cf4f3c", 118 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 119 | mac: "51f0bebf7e3b9d92fc49741779363cfe", 120 | }, 121 | { 122 | key: "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", 123 | plain: "", 124 | mac: "d17ddf46adaacde531cac483de7a9367", 125 | }, 126 | // 5 127 | { 128 | key: "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", 129 | plain: "6bc1bee22e409f96e93d7e117393172a", 130 | mac: "9e99a7bf31e710900662f65e617c5184", 131 | }, 132 | { 133 | key: "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", 134 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411", 135 | mac: "8a1de5be2eb31aad089a82e6ee908b0e", 136 | }, 137 | { 138 | key: "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", 139 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 140 | mac: "a1d5df0eed790f794d77589659f39a11", 141 | }, 142 | { 143 | key: "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 144 | plain: "", 145 | mac: "028962f61b7bf89efc6b551f4667d983", 146 | }, 147 | { 148 | key: "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 149 | plain: "6bc1bee22e409f96e93d7e117393172a", 150 | mac: "28a7023f452e8f82bd4bf28d8c37c35c", 151 | }, 152 | // 10 153 | { 154 | key: "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 155 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411", 156 | mac: "aaf3d8f1de5640c232f5b169b9c911e6", 157 | }, 158 | { 159 | key: "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", 160 | plain: "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710", 161 | mac: "e1992190549f6ed5696a2c056c315410", 162 | }, 163 | } 164 | 165 | for i, test := range tests { 166 | refKey, _ := hex.DecodeString(test.key) 167 | plain, _ := hex.DecodeString(test.plain) 168 | refMac, _ := hex.DecodeString(test.mac) 169 | cm, err := New(aes.NewCipher, refKey) 170 | if err != nil { 171 | panic(err) 172 | } 173 | cm.Reset() 174 | n, err := cm.Write(plain) 175 | if err != nil { 176 | t.Errorf("unexpected error: %s", err) 177 | continue 178 | } 179 | if len(plain) != n { 180 | t.Errorf("got len %d, expected %d for test %d", n, len(plain), i) 181 | continue 182 | } 183 | if !Equal(cm.Sum(nil), refMac) { 184 | t.Errorf("mac mismatch for test %d", i) 185 | } 186 | } 187 | } 188 | 189 | func TestMultiWrite(t *testing.T) { 190 | key := "2b7e151628aed2a6abf7158809cf4f3c" 191 | keyBytes, _ := hex.DecodeString(key) 192 | 193 | msg := "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710" 194 | msgBytes, _ := hex.DecodeString(msg) 195 | 196 | mac := "51f0bebf7e3b9d92fc49741779363cfe" 197 | 198 | cm, err := New(aes.NewCipher, keyBytes) 199 | if err != nil { 200 | t.Fatal("unexpected error: ", err) 201 | } 202 | 203 | b := msgBytes 204 | for len(b) > 7 { 205 | cm.Write(b[:7]) 206 | b = b[7:] 207 | cm.Sum(nil) 208 | } 209 | cm.Write(b) 210 | 211 | macBytes := cm.Sum(nil) 212 | if hex.EncodeToString(macBytes) != mac { 213 | t.Fatalf("mac mismatch") 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/chmike/cmac-go 2 | 3 | go 1.17 4 | --------------------------------------------------------------------------------