SquidDev

AES Pure Lua

May 29th, 2014
1,458
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 27.81 KB | None | 0 0
  1. local function _W(f) local e=setmetatable({}, {__index = _ENV or getfenv()}) if setfenv then setfenv(f, e) end return f(e) or e end
  2. local bit=_W(function(_ENV, ...)
  3. --[[
  4.     This bit API is designed to cope with unsigned integers instead of normal integers
  5.  
  6.     To do this we add checks for overflows: (x > 2^31 ? x - 2 ^ 32 : x)
  7.     These are written in long form because no constant folding.
  8. ]]
  9.  
  10. local floor = math.floor
  11.  
  12. local lshift, rshift
  13.  
  14. rshift = function(a,disp)
  15.     return floor(a % 4294967296 / 2^disp)
  16. end
  17.  
  18. lshift = function(a,disp)
  19.     return (a * 2^disp) % 4294967296
  20. end
  21.  
  22. return {
  23.     -- bit operations
  24.     bnot = bit.bnot,
  25.     band = bit.band,
  26.     bor  = bit.bor,
  27.     bxor = bit.bxor,
  28.     rshift = rshift,
  29.     lshift = lshift,
  30. }
  31. end)
  32. local gf=_W(function(_ENV, ...)
  33. -- finite field with base 2 and modulo irreducible polynom x^8+x^4+x^3+x+1 = 0x11d
  34. local bxor = bit.bxor
  35. local lshift = bit.lshift
  36.  
  37. -- private data of gf
  38. local n = 0x100
  39. local ord = 0xff
  40. local irrPolynom = 0x11b
  41. local exp = {}
  42. local log = {}
  43.  
  44. --
  45. -- add two polynoms (its simply xor)
  46. --
  47. local function add(operand1, operand2)
  48.     return bxor(operand1,operand2)
  49. end
  50.  
  51. --
  52. -- subtract two polynoms (same as addition)
  53. --
  54. local function sub(operand1, operand2)
  55.     return bxor(operand1,operand2)
  56. end
  57.  
  58. --
  59. -- inverts element
  60. -- a^(-1) = g^(order - log(a))
  61. --
  62. local function invert(operand)
  63.     -- special case for 1
  64.     if (operand == 1) then
  65.         return 1
  66.     end
  67.     -- normal invert
  68.     local exponent = ord - log[operand]
  69.     return exp[exponent]
  70. end
  71.  
  72. --
  73. -- multiply two elements using a logarithm table
  74. -- a*b = g^(log(a)+log(b))
  75. --
  76. local function mul(operand1, operand2)
  77.     if (operand1 == 0 or operand2 == 0) then
  78.         return 0
  79.     end
  80.  
  81.     local exponent = log[operand1] + log[operand2]
  82.     if (exponent >= ord) then
  83.         exponent = exponent - ord
  84.     end
  85.     return  exp[exponent]
  86. end
  87.  
  88. --
  89. -- divide two elements
  90. -- a/b = g^(log(a)-log(b))
  91. --
  92. local function div(operand1, operand2)
  93.     if (operand1 == 0)  then
  94.         return 0
  95.     end
  96.     -- TODO: exception if operand2 == 0
  97.     local exponent = log[operand1] - log[operand2]
  98.     if (exponent < 0) then
  99.         exponent = exponent + ord
  100.     end
  101.     return exp[exponent]
  102. end
  103.  
  104. --
  105. -- print logarithmic table
  106. --
  107. local function printLog()
  108.     for i = 1, n do
  109.         print("log(", i-1, ")=", log[i-1])
  110.     end
  111. end
  112.  
  113. --
  114. -- print exponentiation table
  115. --
  116. local function printExp()
  117.     for i = 1, n do
  118.         print("exp(", i-1, ")=", exp[i-1])
  119.     end
  120. end
  121.  
  122. --
  123. -- calculate logarithmic and exponentiation table
  124. --
  125. local function initMulTable()
  126.     local a = 1
  127.  
  128.     for i = 0,ord-1 do
  129.         exp[i] = a
  130.         log[a] = i
  131.  
  132.         -- multiply with generator x+1 -> left shift + 1
  133.         a = bxor(lshift(a, 1), a)
  134.  
  135.         -- if a gets larger than order, reduce modulo irreducible polynom
  136.         if a > ord then
  137.             a = sub(a, irrPolynom)
  138.         end
  139.     end
  140. end
  141.  
  142. initMulTable()
  143.  
  144. return {
  145.     add = add,
  146.     sub = sub,
  147.     invert = invert,
  148.     mul = mul,
  149.     div = dib,
  150.     printLog = printLog,
  151.     printExp = printExp,
  152. }
  153. end)
  154. util=_W(function(_ENV, ...)
  155. -- Cache some bit operators
  156. local bxor = bit.bxor
  157. local rshift = bit.rshift
  158. local band = bit.band
  159. local lshift = bit.lshift
  160.  
  161. local sleepCheckIn
  162. --
  163. -- calculate the parity of one byte
  164. --
  165. local function byteParity(byte)
  166.     byte = bxor(byte, rshift(byte, 4))
  167.     byte = bxor(byte, rshift(byte, 2))
  168.     byte = bxor(byte, rshift(byte, 1))
  169.     return band(byte, 1)
  170. end
  171.  
  172. --
  173. -- get byte at position index
  174. --
  175. local function getByte(number, index)
  176.     if (index == 0) then
  177.         return band(number,0xff)
  178.     else
  179.         return band(rshift(number, index*8),0xff)
  180.     end
  181. end
  182.  
  183.  
  184. --
  185. -- put number into int at position index
  186. --
  187. local function putByte(number, index)
  188.     if (index == 0) then
  189.         return band(number,0xff)
  190.     else
  191.         return lshift(band(number,0xff),index*8)
  192.     end
  193. end
  194.  
  195. --
  196. -- convert byte array to int array
  197. --
  198. local function bytesToInts(bytes, start, n)
  199.     local ints = {}
  200.     for i = 0, n - 1 do
  201.         ints[i + 1] =
  202.                 putByte(bytes[start + (i*4)], 3) +
  203.                 putByte(bytes[start + (i*4) + 1], 2) +
  204.                 putByte(bytes[start + (i*4) + 2], 1) +
  205.                 putByte(bytes[start + (i*4) + 3], 0)
  206.  
  207.         if n % 10000 == 0 then sleepCheckIn() end
  208.     end
  209.     return ints
  210. end
  211.  
  212. --
  213. -- convert int array to byte array
  214. --
  215. local function intsToBytes(ints, output, outputOffset, n)
  216.     n = n or #ints
  217.     for i = 0, n - 1 do
  218.         for j = 0,3 do
  219.             output[outputOffset + i*4 + (3 - j)] = getByte(ints[i + 1], j)
  220.         end
  221.  
  222.         if n % 10000 == 0 then sleepCheckIn() end
  223.     end
  224.     return output
  225. end
  226.  
  227. --
  228. -- convert bytes to hexString
  229. --
  230. local function bytesToHex(bytes)
  231.     local hexBytes = ""
  232.  
  233.     for i,byte in ipairs(bytes) do
  234.         hexBytes = hexBytes .. string.format("%02x ", byte)
  235.     end
  236.  
  237.     return hexBytes
  238. end
  239.  
  240. local function hexToBytes(bytes)
  241.     local out = {}
  242.     for i = 1, #bytes, 2 do
  243.         out[#out + 1] = tonumber(bytes:sub(i, i + 1), 16)
  244.     end
  245.  
  246.     return out
  247. end
  248.  
  249. --
  250. -- convert data to hex string
  251. --
  252. local function toHexString(data)
  253.     local type = type(data)
  254.     if (type == "number") then
  255.         return string.format("%08x",data)
  256.     elseif (type == "table") then
  257.         return bytesToHex(data)
  258.     elseif (type == "string") then
  259.         local bytes = {string.byte(data, 1, #data)}
  260.  
  261.         return bytesToHex(bytes)
  262.     else
  263.         return data
  264.     end
  265. end
  266.  
  267. local function padByteString(data)
  268.     local dataLength = #data
  269.  
  270.     local random1 = math.random(0,255)
  271.     local random2 = math.random(0,255)
  272.  
  273.     local prefix = string.char(random1,
  274.         random2,
  275.         random1,
  276.         random2,
  277.         getByte(dataLength, 3),
  278.         getByte(dataLength, 2),
  279.         getByte(dataLength, 1),
  280.         getByte(dataLength, 0)
  281.     )
  282.  
  283.     data = prefix .. data
  284.  
  285.     local paddingLength = math.ceil(#data/16)*16 - #data
  286.     local padding = ""
  287.     for i=1,paddingLength do
  288.         padding = padding .. string.char(math.random(0,255))
  289.     end
  290.  
  291.     return data .. padding
  292. end
  293.  
  294. local function properlyDecrypted(data)
  295.     local random = {string.byte(data,1,4)}
  296.  
  297.     if (random[1] == random[3] and random[2] == random[4]) then
  298.         return true
  299.     end
  300.  
  301.     return false
  302. end
  303.  
  304. local function unpadByteString(data)
  305.     if (not properlyDecrypted(data)) then
  306.         return nil
  307.     end
  308.  
  309.     local dataLength = putByte(string.byte(data,5), 3)
  310.                      + putByte(string.byte(data,6), 2)
  311.                      + putByte(string.byte(data,7), 1)
  312.                      + putByte(string.byte(data,8), 0)
  313.  
  314.     return string.sub(data,9,8+dataLength)
  315. end
  316.  
  317. local function xorIV(data, iv)
  318.     for i = 1,16 do
  319.         data[i] = bxor(data[i], iv[i])
  320.     end
  321. end
  322.  
  323. -- Called every encryption cycle
  324. local push, pull, time = os.queueEvent, coroutine.yield, os.time
  325. local oldTime = time()
  326. local function sleepCheckIn()
  327.     local newTime = time()
  328.     if newTime - oldTime >= 0.03 then -- (0.020 * 1.5)
  329.         oldTime = newTime
  330.         push("sleep")
  331.         pull("sleep")
  332.     end
  333. end
  334.  
  335. local function getRandomData(bytes)
  336.     local char, random, sleep, insert = string.char, math.random, sleepCheckIn, table.insert
  337.     local result = {}
  338.  
  339.     for i=1,bytes do
  340.         insert(result, random(0,255))
  341.         if i % 10240 == 0 then sleep() end
  342.     end
  343.  
  344.     return result
  345. end
  346.  
  347. local function getRandomString(bytes)
  348.     local char, random, sleep, insert = string.char, math.random, sleepCheckIn, table.insert
  349.     local result = {}
  350.  
  351.     for i=1,bytes do
  352.         insert(result, char(random(0,255)))
  353.         if i % 10240 == 0 then sleep() end
  354.     end
  355.  
  356.     return table.concat(result)
  357. end
  358.  
  359. return {
  360.     byteParity = byteParity,
  361.     getByte = getByte,
  362.     putByte = putByte,
  363.     bytesToInts = bytesToInts,
  364.     intsToBytes = intsToBytes,
  365.     bytesToHex = bytesToHex,
  366.     hexToBytes = hexToBytes,
  367.     toHexString = toHexString,
  368.     padByteString = padByteString,
  369.     properlyDecrypted = properlyDecrypted,
  370.     unpadByteString = unpadByteString,
  371.     xorIV = xorIV,
  372.  
  373.     sleepCheckIn = sleepCheckIn,
  374.  
  375.     getRandomData = getRandomData,
  376.     getRandomString = getRandomString,
  377. }
  378. end)
  379. aes=_W(function(_ENV, ...)
  380. -- Implementation of AES with nearly pure lua
  381. -- AES with lua is slow, really slow :-)
  382.  
  383. local putByte = util.putByte
  384. local getByte = util.getByte
  385.  
  386. -- some constants
  387. local ROUNDS = 'rounds'
  388. local KEY_TYPE = "type"
  389. local ENCRYPTION_KEY=1
  390. local DECRYPTION_KEY=2
  391.  
  392. -- aes SBOX
  393. local SBox = {}
  394. local iSBox = {}
  395.  
  396. -- aes tables
  397. local table0 = {}
  398. local table1 = {}
  399. local table2 = {}
  400. local table3 = {}
  401.  
  402. local tableInv0 = {}
  403. local tableInv1 = {}
  404. local tableInv2 = {}
  405. local tableInv3 = {}
  406.  
  407. -- round constants
  408. local rCon = {
  409.     0x01000000,
  410.     0x02000000,
  411.     0x04000000,
  412.     0x08000000,
  413.     0x10000000,
  414.     0x20000000,
  415.     0x40000000,
  416.     0x80000000,
  417.     0x1b000000,
  418.     0x36000000,
  419.     0x6c000000,
  420.     0xd8000000,
  421.     0xab000000,
  422.     0x4d000000,
  423.     0x9a000000,
  424.     0x2f000000,
  425. }
  426.  
  427. --
  428. -- affine transformation for calculating the S-Box of AES
  429. --
  430. local function affinMap(byte)
  431.     mask = 0xf8
  432.     result = 0
  433.     for i = 1,8 do
  434.         result = bit.lshift(result,1)
  435.  
  436.         parity = util.byteParity(bit.band(byte,mask))
  437.         result = result + parity
  438.  
  439.         -- simulate roll
  440.         lastbit = bit.band(mask, 1)
  441.         mask = bit.band(bit.rshift(mask, 1),0xff)
  442.         if (lastbit ~= 0) then
  443.             mask = bit.bor(mask, 0x80)
  444.         else
  445.             mask = bit.band(mask, 0x7f)
  446.         end
  447.     end
  448.  
  449.     return bit.bxor(result, 0x63)
  450. end
  451.  
  452. --
  453. -- calculate S-Box and inverse S-Box of AES
  454. -- apply affine transformation to inverse in finite field 2^8
  455. --
  456. local function calcSBox()
  457.     for i = 0, 255 do
  458.     if (i ~= 0) then
  459.         inverse = gf.invert(i)
  460.     else
  461.         inverse = i
  462.     end
  463.         mapped = affinMap(inverse)
  464.         SBox[i] = mapped
  465.         iSBox[mapped] = i
  466.     end
  467. end
  468.  
  469. --
  470. -- Calculate round tables
  471. -- round tables are used to calculate shiftRow, MixColumn and SubBytes
  472. -- with 4 table lookups and 4 xor operations.
  473. --
  474. local function calcRoundTables()
  475.     for x = 0,255 do
  476.         byte = SBox[x]
  477.         table0[x] = putByte(gf.mul(0x03, byte), 0)
  478.                           + putByte(             byte , 1)
  479.                           + putByte(             byte , 2)
  480.                           + putByte(gf.mul(0x02, byte), 3)
  481.         table1[x] = putByte(             byte , 0)
  482.                           + putByte(             byte , 1)
  483.                           + putByte(gf.mul(0x02, byte), 2)
  484.                           + putByte(gf.mul(0x03, byte), 3)
  485.         table2[x] = putByte(             byte , 0)
  486.                           + putByte(gf.mul(0x02, byte), 1)
  487.                           + putByte(gf.mul(0x03, byte), 2)
  488.                           + putByte(             byte , 3)
  489.         table3[x] = putByte(gf.mul(0x02, byte), 0)
  490.                           + putByte(gf.mul(0x03, byte), 1)
  491.                           + putByte(             byte , 2)
  492.                           + putByte(             byte , 3)
  493.     end
  494. end
  495.  
  496. --
  497. -- Calculate inverse round tables
  498. -- does the inverse of the normal roundtables for the equivalent
  499. -- decryption algorithm.
  500. --
  501. local function calcInvRoundTables()
  502.     for x = 0,255 do
  503.         byte = iSBox[x]
  504.         tableInv0[x] = putByte(gf.mul(0x0b, byte), 0)
  505.                              + putByte(gf.mul(0x0d, byte), 1)
  506.                              + putByte(gf.mul(0x09, byte), 2)
  507.                              + putByte(gf.mul(0x0e, byte), 3)
  508.         tableInv1[x] = putByte(gf.mul(0x0d, byte), 0)
  509.                              + putByte(gf.mul(0x09, byte), 1)
  510.                              + putByte(gf.mul(0x0e, byte), 2)
  511.                              + putByte(gf.mul(0x0b, byte), 3)
  512.         tableInv2[x] = putByte(gf.mul(0x09, byte), 0)
  513.                              + putByte(gf.mul(0x0e, byte), 1)
  514.                              + putByte(gf.mul(0x0b, byte), 2)
  515.                              + putByte(gf.mul(0x0d, byte), 3)
  516.         tableInv3[x] = putByte(gf.mul(0x0e, byte), 0)
  517.                              + putByte(gf.mul(0x0b, byte), 1)
  518.                              + putByte(gf.mul(0x0d, byte), 2)
  519.                              + putByte(gf.mul(0x09, byte), 3)
  520.     end
  521. end
  522.  
  523.  
  524. --
  525. -- rotate word: 0xaabbccdd gets 0xbbccddaa
  526. -- used for key schedule
  527. --
  528. local function rotWord(word)
  529.     local tmp = bit.band(word,0xff000000)
  530.     return (bit.lshift(word,8) + bit.rshift(tmp,24))
  531. end
  532.  
  533. --
  534. -- replace all bytes in a word with the SBox.
  535. -- used for key schedule
  536. --
  537. local function subWord(word)
  538.     return putByte(SBox[getByte(word,0)],0)
  539.         + putByte(SBox[getByte(word,1)],1)
  540.         + putByte(SBox[getByte(word,2)],2)
  541.         + putByte(SBox[getByte(word,3)],3)
  542. end
  543.  
  544. --
  545. -- generate key schedule for aes encryption
  546. --
  547. -- returns table with all round keys and
  548. -- the necessary number of rounds saved in [ROUNDS]
  549. --
  550. local function expandEncryptionKey(key)
  551.     local keySchedule = {}
  552.     local keyWords = math.floor(#key / 4)
  553.  
  554.  
  555.     if ((keyWords ~= 4 and keyWords ~= 6 and keyWords ~= 8) or (keyWords * 4 ~= #key)) then
  556.         error("Invalid key size: " .. tostring(keyWords))
  557.         return nil
  558.     end
  559.  
  560.     keySchedule[ROUNDS] = keyWords + 6
  561.     keySchedule[KEY_TYPE] = ENCRYPTION_KEY
  562.  
  563.     for i = 0,keyWords - 1 do
  564.         keySchedule[i] = putByte(key[i*4+1], 3)
  565.                        + putByte(key[i*4+2], 2)
  566.                        + putByte(key[i*4+3], 1)
  567.                        + putByte(key[i*4+4], 0)
  568.     end
  569.  
  570.     for i = keyWords, (keySchedule[ROUNDS] + 1)*4 - 1 do
  571.         local tmp = keySchedule[i-1]
  572.  
  573.         if ( i % keyWords == 0) then
  574.             tmp = rotWord(tmp)
  575.             tmp = subWord(tmp)
  576.  
  577.             local index = math.floor(i/keyWords)
  578.             tmp = bit.bxor(tmp,rCon[index])
  579.         elseif (keyWords > 6 and i % keyWords == 4) then
  580.             tmp = subWord(tmp)
  581.         end
  582.  
  583.         keySchedule[i] = bit.bxor(keySchedule[(i-keyWords)],tmp)
  584.     end
  585.  
  586.     return keySchedule
  587. end
  588.  
  589. --
  590. -- Inverse mix column
  591. -- used for key schedule of decryption key
  592. --
  593. local function invMixColumnOld(word)
  594.     local b0 = getByte(word,3)
  595.     local b1 = getByte(word,2)
  596.     local b2 = getByte(word,1)
  597.     local b3 = getByte(word,0)
  598.  
  599.     return putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b1),
  600.                                              gf.mul(0x0d, b2)),
  601.                                              gf.mul(0x09, b3)),
  602.                                              gf.mul(0x0e, b0)),3)
  603.          + putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b2),
  604.                                              gf.mul(0x0d, b3)),
  605.                                              gf.mul(0x09, b0)),
  606.                                              gf.mul(0x0e, b1)),2)
  607.          + putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b3),
  608.                                              gf.mul(0x0d, b0)),
  609.                                              gf.mul(0x09, b1)),
  610.                                              gf.mul(0x0e, b2)),1)
  611.          + putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b0),
  612.                                              gf.mul(0x0d, b1)),
  613.                                              gf.mul(0x09, b2)),
  614.                                              gf.mul(0x0e, b3)),0)
  615. end
  616.  
  617. --
  618. -- Optimized inverse mix column
  619. -- look at http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
  620. -- TODO: make it work
  621. --
  622. local function invMixColumn(word)
  623.     local b0 = getByte(word,3)
  624.     local b1 = getByte(word,2)
  625.     local b2 = getByte(word,1)
  626.     local b3 = getByte(word,0)
  627.  
  628.     local t = bit.bxor(b3,b2)
  629.     local u = bit.bxor(b1,b0)
  630.     local v = bit.bxor(t,u)
  631.     v = bit.bxor(v,gf.mul(0x08,v))
  632.     w = bit.bxor(v,gf.mul(0x04, bit.bxor(b2,b0)))
  633.     v = bit.bxor(v,gf.mul(0x04, bit.bxor(b3,b1)))
  634.  
  635.     return putByte( bit.bxor(bit.bxor(b3,v), gf.mul(0x02, bit.bxor(b0,b3))), 0)
  636.          + putByte( bit.bxor(bit.bxor(b2,w), gf.mul(0x02, t              )), 1)
  637.          + putByte( bit.bxor(bit.bxor(b1,v), gf.mul(0x02, bit.bxor(b0,b3))), 2)
  638.          + putByte( bit.bxor(bit.bxor(b0,w), gf.mul(0x02, u              )), 3)
  639. end
  640.  
  641. --
  642. -- generate key schedule for aes decryption
  643. --
  644. -- uses key schedule for aes encryption and transforms each
  645. -- key by inverse mix column.
  646. --
  647. local function expandDecryptionKey(key)
  648.     local keySchedule = expandEncryptionKey(key)
  649.     if (keySchedule == nil) then
  650.         return nil
  651.     end
  652.  
  653.     keySchedule[KEY_TYPE] = DECRYPTION_KEY
  654.  
  655.     for i = 4, (keySchedule[ROUNDS] + 1)*4 - 5 do
  656.         keySchedule[i] = invMixColumnOld(keySchedule[i])
  657.     end
  658.  
  659.     return keySchedule
  660. end
  661.  
  662. --
  663. -- xor round key to state
  664. --
  665. local function addRoundKey(state, key, round)
  666.     for i = 0, 3 do
  667.         state[i + 1] = bit.bxor(state[i + 1], key[round*4+i])
  668.     end
  669. end
  670.  
  671. --
  672. -- do encryption round (ShiftRow, SubBytes, MixColumn together)
  673. --
  674. local function doRound(origState, dstState)
  675.     dstState[1] =  bit.bxor(bit.bxor(bit.bxor(
  676.                 table0[getByte(origState[1],3)],
  677.                 table1[getByte(origState[2],2)]),
  678.                 table2[getByte(origState[3],1)]),
  679.                 table3[getByte(origState[4],0)])
  680.  
  681.     dstState[2] =  bit.bxor(bit.bxor(bit.bxor(
  682.                 table0[getByte(origState[2],3)],
  683.                 table1[getByte(origState[3],2)]),
  684.                 table2[getByte(origState[4],1)]),
  685.                 table3[getByte(origState[1],0)])
  686.  
  687.     dstState[3] =  bit.bxor(bit.bxor(bit.bxor(
  688.                 table0[getByte(origState[3],3)],
  689.                 table1[getByte(origState[4],2)]),
  690.                 table2[getByte(origState[1],1)]),
  691.                 table3[getByte(origState[2],0)])
  692.  
  693.     dstState[4] =  bit.bxor(bit.bxor(bit.bxor(
  694.                 table0[getByte(origState[4],3)],
  695.                 table1[getByte(origState[1],2)]),
  696.                 table2[getByte(origState[2],1)]),
  697.                 table3[getByte(origState[3],0)])
  698. end
  699.  
  700. --
  701. -- do last encryption round (ShiftRow and SubBytes)
  702. --
  703. local function doLastRound(origState, dstState)
  704.     dstState[1] = putByte(SBox[getByte(origState[1],3)], 3)
  705.                 + putByte(SBox[getByte(origState[2],2)], 2)
  706.                 + putByte(SBox[getByte(origState[3],1)], 1)
  707.                 + putByte(SBox[getByte(origState[4],0)], 0)
  708.  
  709.     dstState[2] = putByte(SBox[getByte(origState[2],3)], 3)
  710.                 + putByte(SBox[getByte(origState[3],2)], 2)
  711.                 + putByte(SBox[getByte(origState[4],1)], 1)
  712.                 + putByte(SBox[getByte(origState[1],0)], 0)
  713.  
  714.     dstState[3] = putByte(SBox[getByte(origState[3],3)], 3)
  715.                 + putByte(SBox[getByte(origState[4],2)], 2)
  716.                 + putByte(SBox[getByte(origState[1],1)], 1)
  717.                 + putByte(SBox[getByte(origState[2],0)], 0)
  718.  
  719.     dstState[4] = putByte(SBox[getByte(origState[4],3)], 3)
  720.                 + putByte(SBox[getByte(origState[1],2)], 2)
  721.                 + putByte(SBox[getByte(origState[2],1)], 1)
  722.                 + putByte(SBox[getByte(origState[3],0)], 0)
  723. end
  724.  
  725. --
  726. -- do decryption round
  727. --
  728. local function doInvRound(origState, dstState)
  729.     dstState[1] =  bit.bxor(bit.bxor(bit.bxor(
  730.                 tableInv0[getByte(origState[1],3)],
  731.                 tableInv1[getByte(origState[4],2)]),
  732.                 tableInv2[getByte(origState[3],1)]),
  733.                 tableInv3[getByte(origState[2],0)])
  734.  
  735.     dstState[2] =  bit.bxor(bit.bxor(bit.bxor(
  736.                 tableInv0[getByte(origState[2],3)],
  737.                 tableInv1[getByte(origState[1],2)]),
  738.                 tableInv2[getByte(origState[4],1)]),
  739.                 tableInv3[getByte(origState[3],0)])
  740.  
  741.     dstState[3] =  bit.bxor(bit.bxor(bit.bxor(
  742.                 tableInv0[getByte(origState[3],3)],
  743.                 tableInv1[getByte(origState[2],2)]),
  744.                 tableInv2[getByte(origState[1],1)]),
  745.                 tableInv3[getByte(origState[4],0)])
  746.  
  747.     dstState[4] =  bit.bxor(bit.bxor(bit.bxor(
  748.                 tableInv0[getByte(origState[4],3)],
  749.                 tableInv1[getByte(origState[3],2)]),
  750.                 tableInv2[getByte(origState[2],1)]),
  751.                 tableInv3[getByte(origState[1],0)])
  752. end
  753.  
  754. --
  755. -- do last decryption round
  756. --
  757. local function doInvLastRound(origState, dstState)
  758.     dstState[1] = putByte(iSBox[getByte(origState[1],3)], 3)
  759.                 + putByte(iSBox[getByte(origState[4],2)], 2)
  760.                 + putByte(iSBox[getByte(origState[3],1)], 1)
  761.                 + putByte(iSBox[getByte(origState[2],0)], 0)
  762.  
  763.     dstState[2] = putByte(iSBox[getByte(origState[2],3)], 3)
  764.                 + putByte(iSBox[getByte(origState[1],2)], 2)
  765.                 + putByte(iSBox[getByte(origState[4],1)], 1)
  766.                 + putByte(iSBox[getByte(origState[3],0)], 0)
  767.  
  768.     dstState[3] = putByte(iSBox[getByte(origState[3],3)], 3)
  769.                 + putByte(iSBox[getByte(origState[2],2)], 2)
  770.                 + putByte(iSBox[getByte(origState[1],1)], 1)
  771.                 + putByte(iSBox[getByte(origState[4],0)], 0)
  772.  
  773.     dstState[4] = putByte(iSBox[getByte(origState[4],3)], 3)
  774.                 + putByte(iSBox[getByte(origState[3],2)], 2)
  775.                 + putByte(iSBox[getByte(origState[2],1)], 1)
  776.                 + putByte(iSBox[getByte(origState[1],0)], 0)
  777. end
  778.  
  779. --
  780. -- encrypts 16 Bytes
  781. -- key           encryption key schedule
  782. -- input         array with input data
  783. -- inputOffset   start index for input
  784. -- output        array for encrypted data
  785. -- outputOffset  start index for output
  786. --
  787. local function encrypt(key, input, inputOffset, output, outputOffset)
  788.     --default parameters
  789.     inputOffset = inputOffset or 1
  790.     output = output or {}
  791.     outputOffset = outputOffset or 1
  792.  
  793.     local state = {}
  794.     local tmpState = {}
  795.  
  796.     if (key[KEY_TYPE] ~= ENCRYPTION_KEY) then
  797.         error("No encryption key: " .. tostring(key[KEY_TYPE]) .. ", expected " .. ENCRYPTION_KEY)
  798.         return
  799.     end
  800.  
  801.     state = util.bytesToInts(input, inputOffset, 4)
  802.     addRoundKey(state, key, 0)
  803.  
  804.  
  805.     local round = 1
  806.     while (round < key[ROUNDS] - 1) do
  807.         -- do a double round to save temporary assignments
  808.         doRound(state, tmpState)
  809.         addRoundKey(tmpState, key, round)
  810.         round = round + 1
  811.  
  812.         doRound(tmpState, state)
  813.         addRoundKey(state, key, round)
  814.         round = round + 1
  815.     end
  816.  
  817.     doRound(state, tmpState)
  818.     addRoundKey(tmpState, key, round)
  819.     round = round +1
  820.  
  821.     doLastRound(tmpState, state)
  822.     addRoundKey(state, key, round)
  823.  
  824.     util.sleepCheckIn()
  825.     return util.intsToBytes(state, output, outputOffset)
  826. end
  827.  
  828. --
  829. -- decrypt 16 bytes
  830. -- key           decryption key schedule
  831. -- input         array with input data
  832. -- inputOffset   start index for input
  833. -- output        array for decrypted data
  834. -- outputOffset  start index for output
  835. ---
  836. local function decrypt(key, input, inputOffset, output, outputOffset)
  837.     -- default arguments
  838.     inputOffset = inputOffset or 1
  839.     output = output or {}
  840.     outputOffset = outputOffset or 1
  841.  
  842.     local state = {}
  843.     local tmpState = {}
  844.  
  845.     if (key[KEY_TYPE] ~= DECRYPTION_KEY) then
  846.         error("No decryption key: " .. tostring(key[KEY_TYPE]))
  847.         return
  848.     end
  849.  
  850.     state = util.bytesToInts(input, inputOffset, 4)
  851.     addRoundKey(state, key, key[ROUNDS])
  852.  
  853.     local round = key[ROUNDS] - 1
  854.     while (round > 2) do
  855.         -- do a double round to save temporary assignments
  856.         doInvRound(state, tmpState)
  857.         addRoundKey(tmpState, key, round)
  858.         round = round - 1
  859.  
  860.         doInvRound(tmpState, state)
  861.         addRoundKey(state, key, round)
  862.         round = round - 1
  863.     end
  864.  
  865.  
  866.     doInvRound(state, tmpState)
  867.     addRoundKey(tmpState, key, round)
  868.     round = round - 1
  869.  
  870.     doInvLastRound(tmpState, state)
  871.     addRoundKey(state, key, round)
  872.  
  873.     util.sleepCheckIn()
  874.     return util.intsToBytes(state, output, outputOffset)
  875. end
  876.  
  877. -- calculate all tables when loading this file
  878. calcSBox()
  879. calcRoundTables()
  880. calcInvRoundTables()
  881.  
  882. return {
  883.     ROUNDS = ROUNDS,
  884.     KEY_TYPE = KEY_TYPE,
  885.     ENCRYPTION_KEY = ENCRYPTION_KEY,
  886.     DECRYPTION_KEY = DECRYPTION_KEY,
  887.  
  888.     expandEncryptionKey = expandEncryptionKey,
  889.     expandDecryptionKey = expandDecryptionKey,
  890.     encrypt = encrypt,
  891.     decrypt = decrypt,
  892. }
  893. end)
  894. local buffer=_W(function(_ENV, ...)
  895. local function new ()
  896.     return {}
  897. end
  898.  
  899. local function addString (stack, s)
  900.     table.insert(stack, s)
  901. end
  902.  
  903. local function toString (stack)
  904.     return table.concat(stack)
  905. end
  906.  
  907. return {
  908.     new = new,
  909.     addString = addString,
  910.     toString = toString,
  911. }
  912. end)
  913. ciphermode=_W(function(_ENV, ...)
  914. local public = {}
  915.  
  916. --
  917. -- Encrypt strings
  918. -- key - byte array with key
  919. -- string - string to encrypt
  920. -- modefunction - function for cipher mode to use
  921. --
  922.  
  923. local random = math.random
  924. function public.encryptString(key, data, modeFunction, iv)
  925.     if iv then
  926.         local ivCopy = {}
  927.         for i = 1, 16 do ivCopy[i] = iv[i] end
  928.         iv = ivCopy
  929.     else
  930.         iv = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  931.     end
  932.  
  933.     local keySched = aes.expandEncryptionKey(key)
  934.     local encryptedData = buffer.new()
  935.  
  936.     for i = 1, #data/16 do
  937.         local offset = (i-1)*16 + 1
  938.         local byteData = {string.byte(data,offset,offset +15)}
  939.  
  940.         iv = modeFunction(keySched, byteData, iv)
  941.  
  942.         buffer.addString(encryptedData, string.char(unpack(byteData)))
  943.     end
  944.  
  945.     return buffer.toString(encryptedData)
  946. end
  947.  
  948. --
  949. -- the following 4 functions can be used as
  950. -- modefunction for encryptString
  951. --
  952.  
  953. -- Electronic code book mode encrypt function
  954. function public.encryptECB(keySched, byteData, iv)
  955.     aes.encrypt(keySched, byteData, 1, byteData, 1)
  956. end
  957.  
  958. -- Cipher block chaining mode encrypt function
  959. function public.encryptCBC(keySched, byteData, iv)
  960.     util.xorIV(byteData, iv)
  961.     aes.encrypt(keySched, byteData, 1, byteData, 1)
  962.     return byteData
  963. end
  964.  
  965. -- Output feedback mode encrypt function
  966. function public.encryptOFB(keySched, byteData, iv)
  967.     aes.encrypt(keySched, iv, 1, iv, 1)
  968.     util.xorIV(byteData, iv)
  969.     return iv
  970. end
  971.  
  972. -- Cipher feedback mode encrypt function
  973. function public.encryptCFB(keySched, byteData, iv)
  974.     aes.encrypt(keySched, iv, 1, iv, 1)
  975.     util.xorIV(byteData, iv)
  976.     return byteData
  977. end
  978.  
  979. --
  980. -- Decrypt strings
  981. -- key - byte array with key
  982. -- string - string to decrypt
  983. -- modefunction - function for cipher mode to use
  984. --
  985. function public.decryptString(key, data, modeFunction, iv)
  986.     if iv then
  987.         local ivCopy = {}
  988.         for i = 1, 16 do ivCopy[i] = iv[i] end
  989.         iv = ivCopy
  990.     else
  991.         iv = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
  992.     end
  993.  
  994.     local keySched
  995.     if (modeFunction == public.decryptOFB or modeFunction == public.decryptCFB) then
  996.         keySched = aes.expandEncryptionKey(key)
  997.     else
  998.         keySched = aes.expandDecryptionKey(key)
  999.     end
  1000.  
  1001.     local decryptedData = buffer.new()
  1002.  
  1003.     for i = 1, #data/16 do
  1004.         local offset = (i-1)*16 + 1
  1005.         local byteData = {string.byte(data,offset,offset +15)}
  1006.  
  1007.         iv = modeFunction(keySched, byteData, iv)
  1008.  
  1009.         buffer.addString(decryptedData, string.char(unpack(byteData)))
  1010.     end
  1011.  
  1012.     return buffer.toString(decryptedData)
  1013. end
  1014.  
  1015. --
  1016. -- the following 4 functions can be used as
  1017. -- modefunction for decryptString
  1018. --
  1019.  
  1020. -- Electronic code book mode decrypt function
  1021. function public.decryptECB(keySched, byteData, iv)
  1022.     aes.decrypt(keySched, byteData, 1, byteData, 1)
  1023.     return iv
  1024. end
  1025.  
  1026. -- Cipher block chaining mode decrypt function
  1027. function public.decryptCBC(keySched, byteData, iv)
  1028.     local nextIV = {}
  1029.     for j = 1, 16 do nextIV[j] = byteData[j] end
  1030.  
  1031.     aes.decrypt(keySched, byteData, 1, byteData, 1)
  1032.     util.xorIV(byteData, iv)
  1033.  
  1034.     return nextIV
  1035. end
  1036.  
  1037. -- Output feedback mode decrypt function
  1038. function public.decryptOFB(keySched, byteData, iv)
  1039.     aes.encrypt(keySched, iv, 1, iv, 1)
  1040.     util.xorIV(byteData, iv)
  1041.  
  1042.     return iv
  1043. end
  1044.  
  1045. -- Cipher feedback mode decrypt function
  1046. function public.decryptCFB(keySched, byteData, iv)
  1047.     local nextIV = {}
  1048.     for j = 1, 16 do nextIV[j] = byteData[j] end
  1049.  
  1050.     aes.encrypt(keySched, iv, 1, iv, 1)
  1051.     util.xorIV(byteData, iv)
  1052.  
  1053.     return nextIV
  1054. end
  1055.  
  1056. return public
  1057. end)
  1058. -- Simple API for encrypting strings.
  1059. --
  1060. AES128 = 16
  1061. AES192 = 24
  1062. AES256 = 32
  1063.  
  1064. ECBMODE = 1
  1065. CBCMODE = 2
  1066. OFBMODE = 3
  1067. CFBMODE = 4
  1068.  
  1069. local function pwToKey(password, keyLength, iv)
  1070.     local padLength = keyLength
  1071.     if (keyLength == AES192) then
  1072.         padLength = 32
  1073.     end
  1074.  
  1075.     if (padLength > #password) then
  1076.         local postfix = ""
  1077.         for i = 1,padLength - #password do
  1078.             postfix = postfix .. string.char(0)
  1079.         end
  1080.         password = password .. postfix
  1081.     else
  1082.         password = string.sub(password, 1, padLength)
  1083.     end
  1084.  
  1085.     local pwBytes = {string.byte(password,1,#password)}
  1086.     password = ciphermode.encryptString(pwBytes, password, ciphermode.encryptCBC, iv)
  1087.  
  1088.     password = string.sub(password, 1, keyLength)
  1089.  
  1090.     return {string.byte(password,1,#password)}
  1091. end
  1092.  
  1093. --
  1094. -- Encrypts string data with password password.
  1095. -- password  - the encryption key is generated from this string
  1096. -- data      - string to encrypt (must not be too large)
  1097. -- keyLength - length of aes key: 128(default), 192 or 256 Bit
  1098. -- mode      - mode of encryption: ecb, cbc(default), ofb, cfb
  1099. --
  1100. -- mode and keyLength must be the same for encryption and decryption.
  1101. --
  1102. function encrypt(password, data, keyLength, mode, iv)
  1103.     assert(password ~= nil, "Empty password.")
  1104.     assert(password ~= nil, "Empty data.")
  1105.  
  1106.     local mode = mode or CBCMODE
  1107.     local keyLength = keyLength or AES128
  1108.  
  1109.     local key = pwToKey(password, keyLength, iv)
  1110.  
  1111.     local paddedData = util.padByteString(data)
  1112.  
  1113.     if (mode == ECBMODE) then
  1114.         return ciphermode.encryptString(key, paddedData, ciphermode.encryptECB, iv)
  1115.     elseif (mode == CBCMODE) then
  1116.         return ciphermode.encryptString(key, paddedData, ciphermode.encryptCBC, iv)
  1117.     elseif (mode == OFBMODE) then
  1118.         return ciphermode.encryptString(key, paddedData, ciphermode.encryptOFB, iv)
  1119.     elseif (mode == CFBMODE) then
  1120.         return ciphermode.encryptString(key, paddedData, ciphermode.encryptCFB, iv)
  1121.     else
  1122.         return nil
  1123.     end
  1124. end
  1125.  
  1126.  
  1127.  
  1128.  
  1129. --
  1130. -- Decrypts string data with password password.
  1131. -- password  - the decryption key is generated from this string
  1132. -- data      - string to encrypt
  1133. -- keyLength - length of aes key: 128(default), 192 or 256 Bit
  1134. -- mode      - mode of decryption: ecb, cbc(default), ofb, cfb
  1135. --
  1136. -- mode and keyLength must be the same for encryption and decryption.
  1137. --
  1138. function decrypt(password, data, keyLength, mode, iv)
  1139.     local mode = mode or CBCMODE
  1140.     local keyLength = keyLength or AES128
  1141.  
  1142.     local key = pwToKey(password, keyLength, iv)
  1143.  
  1144.     local plain
  1145.     if (mode == ECBMODE) then
  1146.         plain = ciphermode.decryptString(key, data, ciphermode.decryptECB, iv)
  1147.     elseif (mode == CBCMODE) then
  1148.         plain = ciphermode.decryptString(key, data, ciphermode.decryptCBC, iv)
  1149.     elseif (mode == OFBMODE) then
  1150.         plain = ciphermode.decryptString(key, data, ciphermode.decryptOFB, iv)
  1151.     elseif (mode == CFBMODE) then
  1152.         plain = ciphermode.decryptString(key, data, ciphermode.decryptCFB, iv)
  1153.     end
  1154.  
  1155.     result = util.unpadByteString(plain)
  1156.  
  1157.     if (result == nil) then
  1158.         return nil
  1159.     end
  1160.  
  1161.     return result
  1162. end
Advertisement
Add Comment
Please, Sign In to add comment