Created
October 24, 2018 01:44
-
-
Save Wavesonics/bf1fd210854a4824d053f52925379e3f to your computer and use it in GitHub Desktop.
Kotlin implementation of Optimus integer hashing algorithm https://github.com/jenssegers/optimus
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Optimus(private val prime: Int, | |
private val randomNumber: Int, | |
private val modInverse: Int = ModInverse(prime)) | |
{ | |
init | |
{ | |
if (!isProbablyPrime(prime)) throw IllegalArgumentException("$prime is not a prime number") | |
} | |
fun encode(n: Int): Int = n * this.prime and MAX_INT xor this.randomNumber | |
fun decode(n: Int): Int = (n xor this.randomNumber) * this.modInverse and MAX_INT | |
companion object | |
{ | |
private const val MAX_INT = Integer.MAX_VALUE | |
private fun ModInverse(n: Int): Int | |
{ | |
val p = BigInteger.valueOf(n.toLong()) | |
val l = java.lang.Long.valueOf(MAX_INT.toLong()) + 1L | |
val m = BigInteger.valueOf(l) | |
return p.modInverse(m).toInt() | |
} | |
private fun isProbablyPrime(n: Int): Boolean | |
{ | |
return BigInteger.valueOf((n - 1).toLong()).nextProbablePrime() == BigInteger.valueOf(n.toLong()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment