1. import java.io.IOException;
  2. import java.nio.charset.StandardCharsets;
  3. import java.util.Base64;
  4. public class CookieHasher {
  5. /**
  6. * Hashes a session cookie value with optional salt and encoding.
  7. * @param cookieValue The session cookie value to hash.
  8. * @param salt Optional salt value to use for hashing.
  9. * @param encode Optional boolean indicating whether to encode the result in Base64.
  10. * @return The hashed value as a string.
  11. * @throws IllegalArgumentException if cookieValue is null.
  12. */
  13. public static String hashCookie(String cookieValue, String salt, boolean encode) {
  14. if (cookieValue == null) {
  15. throw new IllegalArgumentException("Cookie value cannot be null.");
  16. }
  17. String data = cookieValue + (salt != null ? salt : ""); //Concatenate cookie and salt
  18. byte[] bytes = data.getBytes(StandardCharsets.UTF_8); // Convert to bytes
  19. // Simple hash implementation (can be replaced with a more robust algorithm)
  20. int hash = 0;
  21. for (byte b : bytes) {
  22. hash = (hash * 31 + b) % 1000000007; // A prime number for modulo
  23. }
  24. String hashString = String.valueOf(hash);
  25. if (encode) {
  26. byte[] encodedBytes = Base64.getEncoder().encode(hashString.getBytes(StandardCharsets.UTF_8));
  27. return new String(encodedBytes, StandardCharsets.UTF_8);
  28. } else {
  29. return hashString;
  30. }
  31. }
  32. public static void main(String[] args) {
  33. //Example Usage
  34. String cookie = "abcdef123456";
  35. String salt = "mySecretSalt";
  36. String hashedValue = hashCookie(cookie, null, false); //No salt, no encode
  37. System.out.println("Hashed value: " + hashedValue);
  38. String hashedAndEncoded = hashCookie(cookie, salt, true); //With salt, encode in base64
  39. System.out.println("Hashed and encoded value: " + hashedAndEncoded);
  40. try {
  41. hashCookie(null, null, false);
  42. } catch (IllegalArgumentException e) {
  43. System.out.println("Exception caught: " + e.getMessage());
  44. }
  45. }
  46. }

Add your comment