Created
October 12, 2017 13:47
-
-
Save gofer/71052e1c94aee9791cbe6a1d88d8333c to your computer and use it in GitHub Desktop.
Diffie-Hellman鍵交換アルゴリズム
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
require 'prime' | |
N = 100000 | |
def nth_prime(n) | |
Prime.each.take(n).last | |
end | |
def power(x, n) | |
if n <= 1 then | |
return (n == 1) ? x : 1 | |
end | |
y = power(x, n / 2) | |
z = y * y | |
if (n % 2) == 1 then | |
z = z * x | |
end | |
return z | |
end | |
def diffie_hellman_main(g, n, x, y) | |
p = power(g, x) % n | |
q = power(g, y) % n | |
a = power(q, x) % n | |
b = power(p, y) % n | |
return {:p => p, :q => q, :a => a, :b => b} | |
end | |
def diffie_hellman(g, n) | |
x = Random.rand(N) | |
y = Random.rand(N) | |
return diffie_hellman_main(g, n, x, y) | |
end | |
def main(argv) | |
n = nth_prime(Random.rand(N)) | |
g = Random.rand(n) | |
puts diffie_hellman(g, n).to_s | |
end | |
if self.to_s == 'main' then | |
main(ARGV) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment