1/*
2 * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
8 */
9
10/*
11 * Derived from the BLAKE2 reference implementation written by Samuel Neves.
12 * Copyright 2012, Samuel Neves <sneves@dei.uc.pt>
13 * More information about the BLAKE2 hash function and its implementations
14 * can be found at https://blake2.net.
15 */
16
17#include <string.h>
18
19static ossl_inline uint32_t load32(const uint8_t *src)
20{
21 const union {
22 long one;
23 char little;
24 } is_endian = { 1 };
25
26 if (is_endian.little) {
27 uint32_t w;
28 memcpy(&w, src, sizeof(w));
29 return w;
30 } else {
31 uint32_t w = ((uint32_t)src[0])
32 | ((uint32_t)src[1] << 8)
33 | ((uint32_t)src[2] << 16)
34 | ((uint32_t)src[3] << 24);
35 return w;
36 }
37}
38
39static ossl_inline uint64_t load64(const uint8_t *src)
40{
41 const union {
42 long one;
43 char little;
44 } is_endian = { 1 };
45
46 if (is_endian.little) {
47 uint64_t w;
48 memcpy(&w, src, sizeof(w));
49 return w;
50 } else {
51 uint64_t w = ((uint64_t)src[0])
52 | ((uint64_t)src[1] << 8)
53 | ((uint64_t)src[2] << 16)
54 | ((uint64_t)src[3] << 24)
55 | ((uint64_t)src[4] << 32)
56 | ((uint64_t)src[5] << 40)
57 | ((uint64_t)src[6] << 48)
58 | ((uint64_t)src[7] << 56);
59 return w;
60 }
61}
62
63static ossl_inline void store32(uint8_t *dst, uint32_t w)
64{
65 const union {
66 long one;
67 char little;
68 } is_endian = { 1 };
69
70 if (is_endian.little) {
71 memcpy(dst, &w, sizeof(w));
72 } else {
73 uint8_t *p = (uint8_t *)dst;
74 int i;
75
76 for (i = 0; i < 4; i++)
77 p[i] = (uint8_t)(w >> (8 * i));
78 }
79}
80
81static ossl_inline void store64(uint8_t *dst, uint64_t w)
82{
83 const union {
84 long one;
85 char little;
86 } is_endian = { 1 };
87
88 if (is_endian.little) {
89 memcpy(dst, &w, sizeof(w));
90 } else {
91 uint8_t *p = (uint8_t *)dst;
92 int i;
93
94 for (i = 0; i < 8; i++)
95 p[i] = (uint8_t)(w >> (8 * i));
96 }
97}
98
99static ossl_inline uint64_t load48(const uint8_t *src)
100{
101 uint64_t w = ((uint64_t)src[0])
102 | ((uint64_t)src[1] << 8)
103 | ((uint64_t)src[2] << 16)
104 | ((uint64_t)src[3] << 24)
105 | ((uint64_t)src[4] << 32)
106 | ((uint64_t)src[5] << 40);
107 return w;
108}
109
110static ossl_inline void store48(uint8_t *dst, uint64_t w)
111{
112 uint8_t *p = (uint8_t *)dst;
113 p[0] = (uint8_t)w;
114 p[1] = (uint8_t)(w>>8);
115 p[2] = (uint8_t)(w>>16);
116 p[3] = (uint8_t)(w>>24);
117 p[4] = (uint8_t)(w>>32);
118 p[5] = (uint8_t)(w>>40);
119}
120
121static ossl_inline uint32_t rotr32(const uint32_t w, const unsigned int c)
122{
123 return (w >> c) | (w << (32 - c));
124}
125
126static ossl_inline uint64_t rotr64(const uint64_t w, const unsigned int c)
127{
128 return (w >> c) | (w << (64 - c));
129}
130