Advertisement
Guest User

security

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