| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #include <stdint.h> |
| 16 | #include <string.h> |
| 17 |
| 18 | #include <openssl/siphash.h> |
| 19 |
| 20 | #include "../internal.h" |
| 21 |
| 22 |
| 23 | static void siphash_round(uint64_t v[4]) { |
| 24 | v[0] += v[1]; |
| 25 | v[2] += v[3]; |
| 26 | v[1] = CRYPTO_rotl_u64(v[1], 13); |
| 27 | v[3] = CRYPTO_rotl_u64(v[3], 16); |
| 28 | v[1] ^= v[0]; |
| 29 | v[3] ^= v[2]; |
| 30 | v[0] = CRYPTO_rotl_u64(v[0], 32); |
| 31 | v[2] += v[1]; |
| 32 | v[0] += v[3]; |
| 33 | v[1] = CRYPTO_rotl_u64(v[1], 17); |
| 34 | v[3] = CRYPTO_rotl_u64(v[3], 21); |
| 35 | v[1] ^= v[2]; |
| 36 | v[3] ^= v[0]; |
| 37 | v[2] = CRYPTO_rotl_u64(v[2], 32); |
| 38 | } |
| 39 |
| 40 | uint64_t SIPHASH_24(const uint64_t key[2], const uint8_t *input, |
| 41 | size_t input_len) { |
| 42 | const size_t orig_input_len = input_len; |
| 43 |
| 44 | uint64_t v[4]; |
| 45 | v[0] = key[0] ^ UINT64_C(0x736f6d6570736575); |
| 46 | v[1] = key[1] ^ UINT64_C(0x646f72616e646f6d); |
| 47 | v[2] = key[0] ^ UINT64_C(0x6c7967656e657261); |
| 48 | v[3] = key[1] ^ UINT64_C(0x7465646279746573); |
| 49 |
| 50 | while (input_len >= sizeof(uint64_t)) { |
| 51 | uint64_t m = CRYPTO_load_u64_le(input); |
| 52 | v[3] ^= m; |
| 53 | siphash_round(v); |
| 54 | siphash_round(v); |
| 55 | v[0] ^= m; |
| 56 |
| 57 | input += sizeof(uint64_t); |
| 58 | input_len -= sizeof(uint64_t); |
| 59 | } |
| 60 |
| 61 | uint8_t last_block[8]; |
| 62 | OPENSSL_memset(last_block, 0, sizeof(last_block)); |
| 63 | OPENSSL_memcpy(last_block, input, input_len); |
| 64 | last_block[7] = orig_input_len & 0xff; |
| 65 |
| 66 | uint64_t last_block_word = CRYPTO_load_u64_le(last_block); |
| 67 | v[3] ^= last_block_word; |
| 68 | siphash_round(v); |
| 69 | siphash_round(v); |
| 70 | v[0] ^= last_block_word; |
| 71 |
| 72 | v[2] ^= 0xff; |
| 73 | siphash_round(v); |
| 74 | siphash_round(v); |
| 75 | siphash_round(v); |
| 76 | siphash_round(v); |
| 77 |
| 78 | return v[0] ^ v[1] ^ v[2] ^ v[3]; |
| 79 | } |
| 80 |