blob: 5fc4558e17dd4d139e159ecb917609a9dec6e345 [file] [log] [blame]
Patrick Ventureef3aead2018-09-12 08:53:29 -07001/*
2 * Copyright 2018 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "crc.hpp"
18
19namespace blobs
20{
21
22void Crc16::clear()
23{
24 value = crc16Initial;
25}
26
27// Origin: security/crypta/ipmi/portable/ipmi_utils.c
28void Crc16::compute(const uint8_t* bytes, uint32_t length)
29{
30 if (!bytes)
31 {
32 return;
33 }
34
35 const int kExtraRounds = 2;
36 const uint16_t kLeftBit = 0x8000;
37 uint16_t crc = value;
38 size_t i, j;
39
40 for (i = 0; i < length + kExtraRounds; ++i)
41 {
42 for (j = 0; j < 8; ++j)
43 {
44 bool xor_flag = crc & kLeftBit;
45 crc <<= 1;
46 // If this isn't an extra round and the current byte's j'th bit
47 // from the left is set, increment the CRC.
48 if (i < length && bytes[i] & (1 << (7 - j)))
49 {
50 crc++;
51 }
52 if (xor_flag)
53 {
54 crc ^= crc16Ccitt;
55 }
56 }
57 }
58
59 value = crc;
60}
61
62uint16_t Crc16::get() const
63{
64 return value;
65}
66} // namespace blobs