import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class CookieHasher {
/**
* Hashes a session cookie value with optional salt and encoding.
* @param cookieValue The session cookie value to hash.
* @param salt Optional salt value to use for hashing.
* @param encode Optional boolean indicating whether to encode the result in Base64.
* @return The hashed value as a string.
* @throws IllegalArgumentException if cookieValue is null.
*/
public static String hashCookie(String cookieValue, String salt, boolean encode) {
if (cookieValue == null) {
throw new IllegalArgumentException("Cookie value cannot be null.");
}
String data = cookieValue + (salt != null ? salt : ""); //Concatenate cookie and salt
byte[] bytes = data.getBytes(StandardCharsets.UTF_8); // Convert to bytes
// Simple hash implementation (can be replaced with a more robust algorithm)
int hash = 0;
for (byte b : bytes) {
hash = (hash * 31 + b) % 1000000007; // A prime number for modulo
}
String hashString = String.valueOf(hash);
if (encode) {
byte[] encodedBytes = Base64.getEncoder().encode(hashString.getBytes(StandardCharsets.UTF_8));
return new String(encodedBytes, StandardCharsets.UTF_8);
} else {
return hashString;
}
}
public static void main(String[] args) {
//Example Usage
String cookie = "abcdef123456";
String salt = "mySecretSalt";
String hashedValue = hashCookie(cookie, null, false); //No salt, no encode
System.out.println("Hashed value: " + hashedValue);
String hashedAndEncoded = hashCookie(cookie, salt, true); //With salt, encode in base64
System.out.println("Hashed and encoded value: " + hashedAndEncoded);
try {
hashCookie(null, null, false);
} catch (IllegalArgumentException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Add your comment