programcreator

AES

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