#!/usr/bin/ruby

######################################
#
# Marcin Woźniak
# s434812
#
#####################################

load 'modul1.rb'

def generator(p,q)
  while true
    g = SecureRandom.random_number(2..p-2)
    if betterExponentiation(g,q,p) == 1
      next
    else
      return g
    end
  end
end

def specyficPrimaryNumber
  while true do
    q = generate(512)
    p = generate(1024)  #2 * q + 1
    puts q 
    puts p
    if primalityTest(q) && primalityTest(p)
      return p,q
    end
  end
end

def codeElGamal(b, g, p, m)
  while true
      k = SecureRandom.random_number(2..p - 2)
      if nwd(k ,p - 1) == 1
        break
      end
  c1 = betterExponentiation(g, k, p)
  c2 = (m * betterExponentiation(b, k, p)) % p
  return c1, c2
  end
end

def decodeElGamal(a, p, c1, c2)
  temp = betterExponentiation(c1, a, p)
  inverse = betterExponentiation(temp, p - 2, p)
  return (c2*inverse) % p
end

starting = Process.clock_gettime(Process::CLOCK_MONOTONIC)

p = generate(2048)
a = SecureRandom.random_number(1..p - 2).to_i
g = SecureRandom.random_number(2..p - 1).to_i
b = betterExponentiation(g, a, p).to_i
m = 289028190829082081290821

code = codeElGamal(b, g, p, m)
c1,c2 = code
puts  code.inspect

decode = decodeElGamal(a, p, c1, c2)

puts decode.inspect


ending = Process.clock_gettime(Process::CLOCK_MONOTONIC)
elapsed = ending - starting
puts "Time " + elapsed.inspect