Advertisement
ViniCastilho

Caesar_RSA.lua

Dec 1st, 2020 (edited)
659
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.69 KB | None | 0 0
  1. os.loadAPI("/Primes.lua")
  2. os.loadAPI("/TableInt.lua")
  3.  
  4. function GetNew(_bitLength)
  5.     local k = {}
  6.     k.p = Primes.GetBetween(19,2^_bitLength)
  7.     k.q = Primes.GetBetween(19,2^_bitLength)
  8.     k.n = k.p * k.q
  9.     k.phi_n = (k.p-1) * (k.q-1)
  10.     local eTable = {}
  11.     local e = 2
  12.     for i = 1, 4 do
  13.         while Primes.GCD2(e,k.phi_n) ~= 1 or Primes.GCD2(e,k.n) ~= 1 do
  14.             e = e + 1
  15.         end
  16.         eTable[i] = e
  17.     end
  18.     k.e = eTable[math.random(1,#eTable)]
  19.     local dTable = {}
  20.     local d = 2
  21.     for i = 1, 4 do
  22.         while (d * k.e) % k.phi_n ~= 1 do
  23.             d = d + 1
  24.         end
  25.         dTable[i] = d
  26.     end
  27.     k.d = dTable[math.random(1,#dTable)]
  28.     local pb = {k.e,k.n}
  29.     pb.e = k.e
  30.     pb.n = k.n
  31.     local pv = {k.d,k.n}
  32.     pv.d = k.d
  33.     pv.n = k.n
  34.     k.public = pb
  35.     k.private = pv
  36.     return k
  37. end
  38.  
  39. function PrintKey(_key)
  40.     print("p = ".._key.p)
  41.     print("q = ".._key.q)
  42.     print("n = ".._key.n)
  43.     print("phi_n = ".._key.phi_n)
  44.     print("e = ".._key.e)
  45.     print("d = ".._key.d)
  46. end
  47.  
  48. function Encrypt(_message,_pair)
  49.     local cipher = ""
  50.     for i = 1, #_message do
  51.         cipher = cipher .. TableInt.Mod(TableInt.Pow(_message:sub(i,i):byte(),_pair[1],'s'),_pair[2]) .. ' '
  52.     end
  53.     return cipher
  54. end
  55.  
  56. function Decrypt(_cipher,_pair)
  57.     local message = ""
  58.     local i = 1
  59.     while i < #_cipher do
  60.         local mChar = ""
  61.         while _cipher:sub(i,i) ~= ' ' do
  62.             mChar = mChar .. _cipher:sub(i,i)
  63.             i = i + 1
  64.         end
  65.         message = message .. string.char(TableInt.Mod(TableInt.Pow(tonumber(mChar),_pair[1],'s'),_pair[2]))
  66.         i = i + 1
  67.     end
  68.     return message
  69. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement