1 /* ykcrc.c --- Implementation of YubiKey CRC-16 function.
2  *
3  * Written by Simon Josefsson <simon@josefsson.org>.
4  * Copyright (c) 2006-2012 Yubico AB
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  *    * Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *
14  *    * Redistributions in binary form must reproduce the above
15  *      copyright notice, this list of conditions and the following
16  *      disclaimer in the documentation and/or other materials provided
17  *      with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  */
32 
33 #include "yubikey.h"
34 
35 uint16_t
yubikey_crc16(const uint8_t * buf,size_t buf_size)36 yubikey_crc16 (const uint8_t * buf, size_t buf_size)
37 {
38   uint16_t m_crc = 0xffff;
39 
40   while (buf_size--)
41     {
42       int i, j;
43       m_crc ^= (uint8_t) * buf++ & 0xFF;
44       for (i = 0; i < 8; i++)
45 	{
46 	  j = m_crc & 1;
47 	  m_crc >>= 1;
48 	  if (j)
49 	    m_crc ^= 0x8408;
50 	}
51     }
52 
53   return m_crc;
54 }
55