Skip to content

Instantly share code, notes, and snippets.

@mkolod
Last active March 3, 2016 06:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkolod/8195fcd884aa61f94210 to your computer and use it in GitHub Desktop.
Save mkolod/8195fcd884aa61f94210 to your computer and use it in GitHub Desktop.
object DiffieHellmanMerkle {
import java.math.BigInteger
import scala.language.implicitConversions
import scala.util.Random
def main(args: Array[String]): Unit =
println(
diffieHellmanMerkle(generator = 3, modulus = 17, alicePrivateKey = 54, bobPrivateKey = 24)
)
implicit def bigIntToInt(i: BigInteger): Int = i.intValue
implicit def intToBigInt(i: Int): BigInteger = new BigInteger(i.toString)
def probRandomPrime(maxBaseForNextPrime: Int = 100, rng: Random = new Random()): Int =
math.abs(rng.nextInt(maxBaseForNextPrime)).nextProbablePrime.intValue
case class DhResult(
generator: Int,
modulus: Int,
alicePrivateKey: Int,
bobPrivateKey: Int,
alicePublicKey: Int,
bobPublicKey: Int,
aliceSharedSecret: Int,
bobSharedSecret: Int
) {
override def toString: String =
s"""DhResult(
generator=$generator, modulus=$modulus, alicePrivateKey=$alicePrivateKey,
bobPrivateKey=$bobPrivateKey, alicePublicKey=$alicePublicKey,
bobPublicKey=$bobPublicKey, aliceSharedSecret=$aliceSharedSecret,
bobSharedSecret=$bobSharedSecret
)"""
}
def diffieHellmanMerkle(
generator: Int = probRandomPrime(maxBaseForNextPrime = 10),
modulus: Int = probRandomPrime(maxBaseForNextPrime = 20),
alicePrivateKey: Int,
bobPrivateKey: Int
): DhResult = {
val alicePublicKey = generator.pow(alicePrivateKey).mod(modulus)
val bobPublicKey = generator.pow(bobPrivateKey).mod(modulus)
val aliceSharedSecret = bobPublicKey.pow(alicePrivateKey).mod(modulus)
val bobSharedSecret = alicePublicKey.pow(bobPrivateKey).mod(modulus)
DhResult(
generator, modulus, alicePrivateKey, bobPrivateKey,
alicePublicKey, bobPublicKey,
aliceSharedSecret, bobSharedSecret
)
}
}
@mkolod
Copy link
Author

mkolod commented Mar 2, 2016

Result (as expected)

    DhResult(
            generator=3, modulus=17, alicePrivateKey=54,
            bobPrivateKey=24, alicePublicKey=15, 
            bobPublicKey=16, aliceSharedSecret=1,
            bobSharedSecret=1
          )

The shared secret is computed for both Alice and Bob to show that they match.

@mkolod
Copy link
Author

mkolod commented Mar 2, 2016

A nice video explanation of Diffie-Hellman-Merkle.

@mkolod
Copy link
Author

mkolod commented Mar 2, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment