create a FnvUtils class in common mapping
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / mapping / FnvUtils.java
1 /*
2  * Copyright © 2020 Orange, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.transportpce.common.mapping;
10
11 import java.math.BigInteger;
12 import java.nio.charset.StandardCharsets;
13 import java.util.Base64;
14
15 public final class FnvUtils {
16
17     //FNV1 64 bit hash constants
18     private static final BigInteger FNV_PRIME = new BigInteger("100000001b3", 16);
19     private static final BigInteger FNV_INIT = new BigInteger("cbf29ce484222325", 16);
20     private static final BigInteger FNV_MOD = new BigInteger("2").pow(64);
21
22     /**
23      * Implements the FNV-1 64bit algorithm.
24      * FNV-1 128bit would be ideal for 16 bytes but we need an overhead for Base64 encoding.
25      * Otherwise, the hash cannot be stored in a UTF-8 string.
26      * https://www.wikiwand.com/en/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function#/FNV-1_hash
27      * https://github.com/pmdamora/fnv-cracker-app/blob/master/src/main/java/passwordcrack/cracking/HashChecker.java
28      * @param stringdata the String to be hashed
29      * @return the hash string
30      */
31     protected static String fnv1_64(String stringdata) {
32         BigInteger hash = FNV_INIT;
33         byte[] data = stringdata.getBytes(StandardCharsets.UTF_8);
34
35         for (byte b : data) {
36             hash = hash.multiply(FNV_PRIME).mod(FNV_MOD);
37             hash = hash.xor(BigInteger.valueOf((int) b & 0xff));
38         }
39
40         return Base64.getEncoder().encodeToString(hash.toByteArray());
41     }
42
43     private FnvUtils() {
44         //Noop - should not be called
45     }
46 }