Skip to content

Instantly share code, notes, and snippets.

@Commandcracker
Last active July 6, 2022 08:33
Show Gist options
  • Save Commandcracker/66f4dc5d80459bcbc5b6420ec66aa97b to your computer and use it in GitHub Desktop.
Save Commandcracker/66f4dc5d80459bcbc5b6420ec66aa97b to your computer and use it in GitHub Desktop.
AES implementation in pur lua for [ComputerCraft](https://github.com/dan200/ComputerCraft) from [SquidDev](https://github.com/SquidDev) / [SquidDev-CC](https://github.com/SquidDev-CC) version 0.5 from [webarchive](https://web.archive.org/web/20200905141349/https://github.com/SquidDev-CC/aeslua) License: [GNU Lesser General Public License](http:/…
local function _W(f) local e=setmetatable({}, {__index = getfenv()}) return setfenv(f,e)() or e end
bit=_W(function()
--[[
This bit API is designed to cope with unsigned integers instead of normal integers
To do this we
]]
local floor = math.floor
local bit_band, bit_bxor = bit.band, bit.bxor
local function band(a, b)
if a > 2147483647 then a = a - 4294967296 end
if b > 2147483647 then b = b - 4294967296 end
return bit_band(a, b)
end
local function bxor(a, b)
if a > 2147483647 then a = a - 4294967296 end
if b > 2147483647 then b = b - 4294967296 end
return bit_bxor(a, b)
end
local lshift, rshift
rshift = function(a,disp)
return floor(a % 4294967296 / 2^disp)
end
lshift = function(a,disp)
return (a * 2^disp) % 4294967296
end
return {
-- bit operations
bnot = bit.bnot,
band = band,
bor = bit.bor,
bxor = bxor,
rshift = rshift,
lshift = lshift,
}
end)
gf=_W(function()
-- finite field with base 2 and modulo irreducible polynom x^8+x^4+x^3+x+1 = 0x11d
local bxor = bit.bxor
local lshift = bit.lshift
-- private data of gf
local n = 0x100
local ord = 0xff
local irrPolynom = 0x11b
local exp = {}
local log = {}
--
-- add two polynoms (its simply xor)
--
local function add(operand1, operand2)
return bxor(operand1,operand2)
end
--
-- subtract two polynoms (same as addition)
--
local function sub(operand1, operand2)
return bxor(operand1,operand2)
end
--
-- inverts element
-- a^(-1) = g^(order - log(a))
--
local function invert(operand)
-- special case for 1
if (operand == 1) then
return 1
end
-- normal invert
local exponent = ord - log[operand]
return exp[exponent]
end
--
-- multiply two elements using a logarithm table
-- a*b = g^(log(a)+log(b))
--
local function mul(operand1, operand2)
if (operand1 == 0 or operand2 == 0) then
return 0
end
local exponent = log[operand1] + log[operand2]
if (exponent >= ord) then
exponent = exponent - ord
end
return exp[exponent]
end
--
-- divide two elements
-- a/b = g^(log(a)-log(b))
--
local function div(operand1, operand2)
if (operand1 == 0) then
return 0
end
-- TODO: exception if operand2 == 0
local exponent = log[operand1] - log[operand2]
if (exponent < 0) then
exponent = exponent + ord
end
return exp[exponent]
end
--
-- print logarithmic table
--
local function printLog()
for i = 1, n do
print("log(", i-1, ")=", log[i-1])
end
end
--
-- print exponentiation table
--
local function printExp()
for i = 1, n do
print("exp(", i-1, ")=", exp[i-1])
end
end
--
-- calculate logarithmic and exponentiation table
--
local function initMulTable()
local a = 1
for i = 0,ord-1 do
exp[i] = a
log[a] = i
-- multiply with generator x+1 -> left shift + 1
a = bxor(lshift(a, 1), a)
-- if a gets larger than order, reduce modulo irreducible polynom
if a > ord then
a = sub(a, irrPolynom)
end
end
end
initMulTable()
return {
add = add,
sub = sub,
invert = invert,
mul = mul,
div = dib,
printLog = printLog,
printExp = printExp,
}
end)
util=_W(function()
-- Cache some bit operators
local bxor = bit.bxor
local rshift = bit.rshift
local band = bit.band
local lshift = bit.lshift
local sleepCheckIn
--
-- calculate the parity of one byte
--
local function byteParity(byte)
byte = bxor(byte, rshift(byte, 4))
byte = bxor(byte, rshift(byte, 2))
byte = bxor(byte, rshift(byte, 1))
return band(byte, 1)
end
--
-- get byte at position index
--
local function getByte(number, index)
if (index == 0) then
return band(number,0xff)
else
return band(rshift(number, index*8),0xff)
end
end
--
-- put number into int at position index
--
local function putByte(number, index)
if (index == 0) then
return band(number,0xff)
else
return lshift(band(number,0xff),index*8)
end
end
--
-- convert byte array to int array
--
local function bytesToInts(bytes, start, n)
local ints = {}
for i = 0, n - 1 do
ints[i] = putByte(bytes[start + (i*4) ], 3)
+ putByte(bytes[start + (i*4) + 1], 2)
+ putByte(bytes[start + (i*4) + 2], 1)
+ putByte(bytes[start + (i*4) + 3], 0)
if n % 10000 == 0 then sleepCheckIn() end
end
return ints
end
--
-- convert int array to byte array
--
local function intsToBytes(ints, output, outputOffset, n)
n = n or #ints
for i = 0, n do
for j = 0,3 do
output[outputOffset + i*4 + (3 - j)] = getByte(ints[i], j)
end
if n % 10000 == 0 then sleepCheckIn() end
end
return output
end
--
-- convert bytes to hexString
--
local function bytesToHex(bytes)
local hexBytes = ""
for i,byte in ipairs(bytes) do
hexBytes = hexBytes .. string.format("%02x ", byte)
end
return hexBytes
end
--
-- convert data to hex string
--
local function toHexString(data)
local type = type(data)
if (type == "number") then
return string.format("%08x",data)
elseif (type == "table") then
return bytesToHex(data)
elseif (type == "string") then
local bytes = {string.byte(data, 1, #data)}
return bytesToHex(bytes)
else
return data
end
end
local function padByteString(data)
local dataLength = #data
local random1 = math.random(0,255)
local random2 = math.random(0,255)
local prefix = string.char(random1,
random2,
random1,
random2,
getByte(dataLength, 3),
getByte(dataLength, 2),
getByte(dataLength, 1),
getByte(dataLength, 0))
data = prefix .. data
local paddingLength = math.ceil(#data/16)*16 - #data
local padding = ""
for i=1,paddingLength do
padding = padding .. string.char(math.random(0,255))
end
return data .. padding
end
local function properlyDecrypted(data)
local random = {string.byte(data,1,4)}
if (random[1] == random[3] and random[2] == random[4]) then
return true
end
return false
end
local function unpadByteString(data)
if (not properlyDecrypted(data)) then
return nil
end
local dataLength = putByte(string.byte(data,5), 3)
+ putByte(string.byte(data,6), 2)
+ putByte(string.byte(data,7), 1)
+ putByte(string.byte(data,8), 0)
return string.sub(data,9,8+dataLength)
end
local function xorIV(data, iv)
for i = 1,16 do
data[i] = bxor(data[i], iv[i])
end
end
-- Called every
local push, pull, time = os.queueEvent, coroutine.yield, os.time
local oldTime = time()
local function sleepCheckIn()
local newTime = time()
if newTime - oldTime >= 0.03 then -- (0.020 * 1.5)
oldTime = newTime
push("sleep")
pull("sleep")
end
end
local function getRandomData(bytes)
local char, random, sleep, insert = string.char, math.random, sleepCheckIn, table.insert
local result = {}
for i=1,bytes do
insert(result, random(0,255))
if i % 10240 == 0 then sleep() end
end
return result
end
local function getRandomString(bytes)
local char, random, sleep, insert = string.char, math.random, sleepCheckIn, table.insert
local result = {}
for i=1,bytes do
insert(result, char(random(0,255)))
if i % 10240 == 0 then sleep() end
end
return table.concat(result)
end
return {
byteParity = byteParity,
getByte = getByte,
putByte = putByte,
bytesToInts = bytesToInts,
intsToBytes = intsToBytes,
bytesToHex = bytesToHex,
toHexString = toHexString,
padByteString = padByteString,
properlyDecrypted = properlyDecrypted,
unpadByteString = unpadByteString,
xorIV = xorIV,
sleepCheckIn = sleepCheckIn,
getRandomData = getRandomData,
getRandomString = getRandomString,
}
end)
aes=_W(function()
-- Implementation of AES with nearly pure lua
-- AES with lua is slow, really slow :-)
local putByte = util.putByte
local getByte = util.getByte
-- some constants
local ROUNDS = 'rounds'
local KEY_TYPE = "type"
local ENCRYPTION_KEY=1
local DECRYPTION_KEY=2
-- aes SBOX
local SBox = {}
local iSBox = {}
-- aes tables
local table0 = {}
local table1 = {}
local table2 = {}
local table3 = {}
local tableInv0 = {}
local tableInv1 = {}
local tableInv2 = {}
local tableInv3 = {}
-- round constants
local rCon = {
0x01000000,
0x02000000,
0x04000000,
0x08000000,
0x10000000,
0x20000000,
0x40000000,
0x80000000,
0x1b000000,
0x36000000,
0x6c000000,
0xd8000000,
0xab000000,
0x4d000000,
0x9a000000,
0x2f000000,
}
--
-- affine transformation for calculating the S-Box of AES
--
local function affinMap(byte)
mask = 0xf8
result = 0
for i = 1,8 do
result = bit.lshift(result,1)
parity = util.byteParity(bit.band(byte,mask))
result = result + parity
-- simulate roll
lastbit = bit.band(mask, 1)
mask = bit.band(bit.rshift(mask, 1),0xff)
if (lastbit ~= 0) then
mask = bit.bor(mask, 0x80)
else
mask = bit.band(mask, 0x7f)
end
end
return bit.bxor(result, 0x63)
end
--
-- calculate S-Box and inverse S-Box of AES
-- apply affine transformation to inverse in finite field 2^8
--
local function calcSBox()
for i = 0, 255 do
if (i ~= 0) then
inverse = gf.invert(i)
else
inverse = i
end
mapped = affinMap(inverse)
SBox[i] = mapped
iSBox[mapped] = i
end
end
--
-- Calculate round tables
-- round tables are used to calculate shiftRow, MixColumn and SubBytes
-- with 4 table lookups and 4 xor operations.
--
local function calcRoundTables()
for x = 0,255 do
byte = SBox[x]
table0[x] = putByte(gf.mul(0x03, byte), 0)
+ putByte( byte , 1)
+ putByte( byte , 2)
+ putByte(gf.mul(0x02, byte), 3)
table1[x] = putByte( byte , 0)
+ putByte( byte , 1)
+ putByte(gf.mul(0x02, byte), 2)
+ putByte(gf.mul(0x03, byte), 3)
table2[x] = putByte( byte , 0)
+ putByte(gf.mul(0x02, byte), 1)
+ putByte(gf.mul(0x03, byte), 2)
+ putByte( byte , 3)
table3[x] = putByte(gf.mul(0x02, byte), 0)
+ putByte(gf.mul(0x03, byte), 1)
+ putByte( byte , 2)
+ putByte( byte , 3)
end
end
--
-- Calculate inverse round tables
-- does the inverse of the normal roundtables for the equivalent
-- decryption algorithm.
--
local function calcInvRoundTables()
for x = 0,255 do
byte = iSBox[x]
tableInv0[x] = putByte(gf.mul(0x0b, byte), 0)
+ putByte(gf.mul(0x0d, byte), 1)
+ putByte(gf.mul(0x09, byte), 2)
+ putByte(gf.mul(0x0e, byte), 3)
tableInv1[x] = putByte(gf.mul(0x0d, byte), 0)
+ putByte(gf.mul(0x09, byte), 1)
+ putByte(gf.mul(0x0e, byte), 2)
+ putByte(gf.mul(0x0b, byte), 3)
tableInv2[x] = putByte(gf.mul(0x09, byte), 0)
+ putByte(gf.mul(0x0e, byte), 1)
+ putByte(gf.mul(0x0b, byte), 2)
+ putByte(gf.mul(0x0d, byte), 3)
tableInv3[x] = putByte(gf.mul(0x0e, byte), 0)
+ putByte(gf.mul(0x0b, byte), 1)
+ putByte(gf.mul(0x0d, byte), 2)
+ putByte(gf.mul(0x09, byte), 3)
end
end
--
-- rotate word: 0xaabbccdd gets 0xbbccddaa
-- used for key schedule
--
local function rotWord(word)
local tmp = bit.band(word,0xff000000)
return (bit.lshift(word,8) + bit.rshift(tmp,24))
end
--
-- replace all bytes in a word with the SBox.
-- used for key schedule
--
local function subWord(word)
return putByte(SBox[getByte(word,0)],0)
+ putByte(SBox[getByte(word,1)],1)
+ putByte(SBox[getByte(word,2)],2)
+ putByte(SBox[getByte(word,3)],3)
end
--
-- generate key schedule for aes encryption
--
-- returns table with all round keys and
-- the necessary number of rounds saved in [ROUNDS]
--
local function expandEncryptionKey(key)
local keySchedule = {}
local keyWords = math.floor(#key / 4)
if ((keyWords ~= 4 and keyWords ~= 6 and keyWords ~= 8) or (keyWords * 4 ~= #key)) then
print("Invalid key size: ", keyWords)
return nil
end
keySchedule[ROUNDS] = keyWords + 6
keySchedule[KEY_TYPE] = ENCRYPTION_KEY
for i = 0,keyWords - 1 do
keySchedule[i] = putByte(key[i*4+1], 3)
+ putByte(key[i*4+2], 2)
+ putByte(key[i*4+3], 1)
+ putByte(key[i*4+4], 0)
end
for i = keyWords, (keySchedule[ROUNDS] + 1)*4 - 1 do
local tmp = keySchedule[i-1]
if ( i % keyWords == 0) then
tmp = rotWord(tmp)
tmp = subWord(tmp)
local index = math.floor(i/keyWords)
tmp = bit.bxor(tmp,rCon[index])
elseif (keyWords > 6 and i % keyWords == 4) then
tmp = subWord(tmp)
end
keySchedule[i] = bit.bxor(keySchedule[(i-keyWords)],tmp)
end
return keySchedule
end
--
-- Inverse mix column
-- used for key schedule of decryption key
--
local function invMixColumnOld(word)
local b0 = getByte(word,3)
local b1 = getByte(word,2)
local b2 = getByte(word,1)
local b3 = getByte(word,0)
return putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b1),
gf.mul(0x0d, b2)),
gf.mul(0x09, b3)),
gf.mul(0x0e, b0)),3)
+ putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b2),
gf.mul(0x0d, b3)),
gf.mul(0x09, b0)),
gf.mul(0x0e, b1)),2)
+ putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b3),
gf.mul(0x0d, b0)),
gf.mul(0x09, b1)),
gf.mul(0x0e, b2)),1)
+ putByte(gf.add(gf.add(gf.add(gf.mul(0x0b, b0),
gf.mul(0x0d, b1)),
gf.mul(0x09, b2)),
gf.mul(0x0e, b3)),0)
end
--
-- Optimized inverse mix column
-- look at http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
-- TODO: make it work
--
local function invMixColumn(word)
local b0 = getByte(word,3)
local b1 = getByte(word,2)
local b2 = getByte(word,1)
local b3 = getByte(word,0)
local t = bit.bxor(b3,b2)
local u = bit.bxor(b1,b0)
local v = bit.bxor(t,u)
v = bit.bxor(v,gf.mul(0x08,v))
w = bit.bxor(v,gf.mul(0x04, bit.bxor(b2,b0)))
v = bit.bxor(v,gf.mul(0x04, bit.bxor(b3,b1)))
return putByte( bit.bxor(bit.bxor(b3,v), gf.mul(0x02, bit.bxor(b0,b3))), 0)
+ putByte( bit.bxor(bit.bxor(b2,w), gf.mul(0x02, t )), 1)
+ putByte( bit.bxor(bit.bxor(b1,v), gf.mul(0x02, bit.bxor(b0,b3))), 2)
+ putByte( bit.bxor(bit.bxor(b0,w), gf.mul(0x02, u )), 3)
end
--
-- generate key schedule for aes decryption
--
-- uses key schedule for aes encryption and transforms each
-- key by inverse mix column.
--
local function expandDecryptionKey(key)
local keySchedule = expandEncryptionKey(key)
if (keySchedule == nil) then
return nil
end
keySchedule[KEY_TYPE] = DECRYPTION_KEY
for i = 4, (keySchedule[ROUNDS] + 1)*4 - 5 do
keySchedule[i] = invMixColumnOld(keySchedule[i])
end
return keySchedule
end
--
-- xor round key to state
--
local function addRoundKey(state, key, round)
for i = 0, 3 do
state[i] = bit.bxor(state[i], key[round*4+i])
end
end
--
-- do encryption round (ShiftRow, SubBytes, MixColumn together)
--
local function doRound(origState, dstState)
dstState[0] = bit.bxor(bit.bxor(bit.bxor(
table0[getByte(origState[0],3)],
table1[getByte(origState[1],2)]),
table2[getByte(origState[2],1)]),
table3[getByte(origState[3],0)])
dstState[1] = bit.bxor(bit.bxor(bit.bxor(
table0[getByte(origState[1],3)],
table1[getByte(origState[2],2)]),
table2[getByte(origState[3],1)]),
table3[getByte(origState[0],0)])
dstState[2] = bit.bxor(bit.bxor(bit.bxor(
table0[getByte(origState[2],3)],
table1[getByte(origState[3],2)]),
table2[getByte(origState[0],1)]),
table3[getByte(origState[1],0)])
dstState[3] = bit.bxor(bit.bxor(bit.bxor(
table0[getByte(origState[3],3)],
table1[getByte(origState[0],2)]),
table2[getByte(origState[1],1)]),
table3[getByte(origState[2],0)])
end
--
-- do last encryption round (ShiftRow and SubBytes)
--
local function doLastRound(origState, dstState)
dstState[0] = putByte(SBox[getByte(origState[0],3)], 3)
+ putByte(SBox[getByte(origState[1],2)], 2)
+ putByte(SBox[getByte(origState[2],1)], 1)
+ putByte(SBox[getByte(origState[3],0)], 0)
dstState[1] = putByte(SBox[getByte(origState[1],3)], 3)
+ putByte(SBox[getByte(origState[2],2)], 2)
+ putByte(SBox[getByte(origState[3],1)], 1)
+ putByte(SBox[getByte(origState[0],0)], 0)
dstState[2] = putByte(SBox[getByte(origState[2],3)], 3)
+ putByte(SBox[getByte(origState[3],2)], 2)
+ putByte(SBox[getByte(origState[0],1)], 1)
+ putByte(SBox[getByte(origState[1],0)], 0)
dstState[3] = putByte(SBox[getByte(origState[3],3)], 3)
+ putByte(SBox[getByte(origState[0],2)], 2)
+ putByte(SBox[getByte(origState[1],1)], 1)
+ putByte(SBox[getByte(origState[2],0)], 0)
end
--
-- do decryption round
--
local function doInvRound(origState, dstState)
dstState[0] = bit.bxor(bit.bxor(bit.bxor(
tableInv0[getByte(origState[0],3)],
tableInv1[getByte(origState[3],2)]),
tableInv2[getByte(origState[2],1)]),
tableInv3[getByte(origState[1],0)])
dstState[1] = bit.bxor(bit.bxor(bit.bxor(
tableInv0[getByte(origState[1],3)],
tableInv1[getByte(origState[0],2)]),
tableInv2[getByte(origState[3],1)]),
tableInv3[getByte(origState[2],0)])
dstState[2] = bit.bxor(bit.bxor(bit.bxor(
tableInv0[getByte(origState[2],3)],
tableInv1[getByte(origState[1],2)]),
tableInv2[getByte(origState[0],1)]),
tableInv3[getByte(origState[3],0)])
dstState[3] = bit.bxor(bit.bxor(bit.bxor(
tableInv0[getByte(origState[3],3)],
tableInv1[getByte(origState[2],2)]),
tableInv2[getByte(origState[1],1)]),
tableInv3[getByte(origState[0],0)])
end
--
-- do last decryption round
--
local function doInvLastRound(origState, dstState)
dstState[0] = putByte(iSBox[getByte(origState[0],3)], 3)
+ putByte(iSBox[getByte(origState[3],2)], 2)
+ putByte(iSBox[getByte(origState[2],1)], 1)
+ putByte(iSBox[getByte(origState[1],0)], 0)
dstState[1] = putByte(iSBox[getByte(origState[1],3)], 3)
+ putByte(iSBox[getByte(origState[0],2)], 2)
+ putByte(iSBox[getByte(origState[3],1)], 1)
+ putByte(iSBox[getByte(origState[2],0)], 0)
dstState[2] = putByte(iSBox[getByte(origState[2],3)], 3)
+ putByte(iSBox[getByte(origState[1],2)], 2)
+ putByte(iSBox[getByte(origState[0],1)], 1)
+ putByte(iSBox[getByte(origState[3],0)], 0)
dstState[3] = putByte(iSBox[getByte(origState[3],3)], 3)
+ putByte(iSBox[getByte(origState[2],2)], 2)
+ putByte(iSBox[getByte(origState[1],1)], 1)
+ putByte(iSBox[getByte(origState[0],0)], 0)
end
--
-- encrypts 16 Bytes
-- key encryption key schedule
-- input array with input data
-- inputOffset start index for input
-- output array for encrypted data
-- outputOffset start index for output
--
local function encrypt(key, input, inputOffset, output, outputOffset)
--default parameters
inputOffset = inputOffset or 1
output = output or {}
outputOffset = outputOffset or 1
local state = {}
local tmpState = {}
if (key[KEY_TYPE] ~= ENCRYPTION_KEY) then
print("No encryption key: ", key[KEY_TYPE])
return
end
state = util.bytesToInts(input, inputOffset, 4)
addRoundKey(state, key, 0)
local checkIn = util.sleepCheckIn
local round = 1
while (round < key[ROUNDS] - 1) do
-- do a double round to save temporary assignments
doRound(state, tmpState)
addRoundKey(tmpState, key, round)
round = round + 1
doRound(tmpState, state)
addRoundKey(state, key, round)
round = round + 1
end
checkIn()
doRound(state, tmpState)
addRoundKey(tmpState, key, round)
round = round +1
doLastRound(tmpState, state)
addRoundKey(state, key, round)
return util.intsToBytes(state, output, outputOffset)
end
--
-- decrypt 16 bytes
-- key decryption key schedule
-- input array with input data
-- inputOffset start index for input
-- output array for decrypted data
-- outputOffset start index for output
---
local function decrypt(key, input, inputOffset, output, outputOffset)
-- default arguments
inputOffset = inputOffset or 1
output = output or {}
outputOffset = outputOffset or 1
local state = {}
local tmpState = {}
if (key[KEY_TYPE] ~= DECRYPTION_KEY) then
print("No decryption key: ", key[KEY_TYPE])
return
end
state = util.bytesToInts(input, inputOffset, 4)
addRoundKey(state, key, key[ROUNDS])
local checkIn = util.sleepCheckIn
local round = key[ROUNDS] - 1
while (round > 2) do
-- do a double round to save temporary assignments
doInvRound(state, tmpState)
addRoundKey(tmpState, key, round)
round = round - 1
doInvRound(tmpState, state)
addRoundKey(state, key, round)
round = round - 1
if round % 32 == 0 then
checkIn()
end
end
checkIn()
doInvRound(state, tmpState)
addRoundKey(tmpState, key, round)
round = round - 1
doInvLastRound(tmpState, state)
addRoundKey(state, key, round)
return util.intsToBytes(state, output, outputOffset)
end
-- calculate all tables when loading this file
calcSBox()
calcRoundTables()
calcInvRoundTables()
return {
ROUNDS = ROUNDS,
KEY_TYPE = KEY_TYPE,
ENCRYPTION_KEY = ENCRYPTION_KEY,
DECRYPTION_KEY = DECRYPTION_KEY,
expandEncryptionKey = expandEncryptionKey,
expandDecryptionKey = expandDecryptionKey,
encrypt = encrypt,
decrypt = decrypt,
}
end)
buffer=_W(function()
local function new ()
return {}
end
local function addString (stack, s)
table.insert(stack, s)
for i = #stack - 1, 1, -1 do
if #stack[i] > #stack[i+1] then
break
end
stack[i] = stack[i] .. table.remove(stack)
end
end
local function toString (stack)
for i = #stack - 1, 1, -1 do
stack[i] = stack[i] .. table.remove(stack)
end
return stack[1]
end
return {
new = new,
addString = addString,
toString = toString,
}
end)
ciphermode=_W(function()
local public = {}
--
-- Encrypt strings
-- key - byte array with key
-- string - string to encrypt
-- modefunction - function for cipher mode to use
--
function public.encryptString(key, data, modeFunction)
local iv = iv or {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local keySched = aes.expandEncryptionKey(key)
local encryptedData = buffer.new()
for i = 1, #data/16 do
local offset = (i-1)*16 + 1
local byteData = {string.byte(data,offset,offset +15)}
modeFunction(keySched, byteData, iv)
buffer.addString(encryptedData, string.char(unpack(byteData)))
end
return buffer.toString(encryptedData)
end
--
-- the following 4 functions can be used as
-- modefunction for encryptString
--
-- Electronic code book mode encrypt function
function public.encryptECB(keySched, byteData, iv)
aes.encrypt(keySched, byteData, 1, byteData, 1)
end
-- Cipher block chaining mode encrypt function
function public.encryptCBC(keySched, byteData, iv)
util.xorIV(byteData, iv)
aes.encrypt(keySched, byteData, 1, byteData, 1)
for j = 1,16 do
iv[j] = byteData[j]
end
end
-- Output feedback mode encrypt function
function public.encryptOFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
util.xorIV(byteData, iv)
end
-- Cipher feedback mode encrypt function
function public.encryptCFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
util.xorIV(byteData, iv)
for j = 1,16 do
iv[j] = byteData[j]
end
end
--
-- Decrypt strings
-- key - byte array with key
-- string - string to decrypt
-- modefunction - function for cipher mode to use
--
function public.decryptString(key, data, modeFunction)
local iv = iv or {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
local keySched
if (modeFunction == public.decryptOFB or modeFunction == public.decryptCFB) then
keySched = aes.expandEncryptionKey(key)
else
keySched = aes.expandDecryptionKey(key)
end
local decryptedData = buffer.new()
for i = 1, #data/16 do
local offset = (i-1)*16 + 1
local byteData = {string.byte(data,offset,offset +15)}
iv = modeFunction(keySched, byteData, iv)
buffer.addString(decryptedData, string.char(unpack(byteData)))
end
return buffer.toString(decryptedData)
end
--
-- the following 4 functions can be used as
-- modefunction for decryptString
--
-- Electronic code book mode decrypt function
function public.decryptECB(keySched, byteData, iv)
aes.decrypt(keySched, byteData, 1, byteData, 1)
return iv
end
-- Cipher block chaining mode decrypt function
function public.decryptCBC(keySched, byteData, iv)
local nextIV = {}
for j = 1,16 do
nextIV[j] = byteData[j]
end
aes.decrypt(keySched, byteData, 1, byteData, 1)
util.xorIV(byteData, iv)
return nextIV
end
-- Output feedback mode decrypt function
function public.decryptOFB(keySched, byteData, iv)
aes.encrypt(keySched, iv, 1, iv, 1)
util.xorIV(byteData, iv)
return iv
end
-- Cipher feedback mode decrypt function
function public.decryptCFB(keySched, byteData, iv)
local nextIV = {}
for j = 1,16 do
nextIV[j] = byteData[j]
end
aes.encrypt(keySched, iv, 1, iv, 1)
util.xorIV(byteData, iv)
return nextIV
end
return public
end)
--@require lib/ciphermode.lua
--@require lib/util.lua
--
-- Simple API for encrypting strings.
--
AES128 = 16
AES192 = 24
AES256 = 32
ECBMODE = 1
CBCMODE = 2
OFBMODE = 3
CFBMODE = 4
local function pwToKey(password, keyLength)
local padLength = keyLength
if (keyLength == AES192) then
padLength = 32
end
if (padLength > #password) then
local postfix = ""
for i = 1,padLength - #password do
postfix = postfix .. string.char(0)
end
password = password .. postfix
else
password = string.sub(password, 1, padLength)
end
local pwBytes = {string.byte(password,1,#password)}
password = ciphermode.encryptString(pwBytes, password, ciphermode.encryptCBC)
password = string.sub(password, 1, keyLength)
return {string.byte(password,1,#password)}
end
--
-- Encrypts string data with password password.
-- password - the encryption key is generated from this string
-- data - string to encrypt (must not be too large)
-- keyLength - length of aes key: 128(default), 192 or 256 Bit
-- mode - mode of encryption: ecb, cbc(default), ofb, cfb
--
-- mode and keyLength must be the same for encryption and decryption.
--
function encrypt(password, data, keyLength, mode)
assert(password ~= nil, "Empty password.")
assert(password ~= nil, "Empty data.")
local mode = mode or CBCMODE
local keyLength = keyLength or AES128
local key = pwToKey(password, keyLength)
local paddedData = util.padByteString(data)
if (mode == ECBMODE) then
return ciphermode.encryptString(key, paddedData, ciphermode.encryptECB)
elseif (mode == CBCMODE) then
return ciphermode.encryptString(key, paddedData, ciphermode.encryptCBC)
elseif (mode == OFBMODE) then
return ciphermode.encryptString(key, paddedData, ciphermode.encryptOFB)
elseif (mode == CFBMODE) then
return ciphermode.encryptString(key, paddedData, ciphermode.encryptCFB)
else
return nil
end
end
--
-- Decrypts string data with password password.
-- password - the decryption key is generated from this string
-- data - string to encrypt
-- keyLength - length of aes key: 128(default), 192 or 256 Bit
-- mode - mode of decryption: ecb, cbc(default), ofb, cfb
--
-- mode and keyLength must be the same for encryption and decryption.
--
function decrypt(password, data, keyLength, mode)
local mode = mode or CBCMODE
local keyLength = keyLength or AES128
local key = pwToKey(password, keyLength)
local plain
if (mode == ECBMODE) then
plain = ciphermode.decryptString(key, data, ciphermode.decryptECB)
elseif (mode == CBCMODE) then
plain = ciphermode.decryptString(key, data, ciphermode.decryptCBC)
elseif (mode == OFBMODE) then
plain = ciphermode.decryptString(key, data, ciphermode.decryptOFB)
elseif (mode == CFBMODE) then
plain = ciphermode.decryptString(key, data, ciphermode.decryptCFB)
end
result = util.unpadByteString(plain)
if (result == nil) then
return nil
end
return result
end
return {}
local function e(a)local o=setmetatable({},{__index=getfenv()})return
setfenv(a,o)()or o end
bit=e(function()
local a=math.floor;local o,i=bit.band,bit.bxor
local function n(d,l)if d>2147483647 then d=d-4294967296 end;if l>
2147483647 then l=l-4294967296 end;return o(d,l)end
local function s(d,l)if d>2147483647 then d=d-4294967296 end;if l>2147483647 then
l=l-4294967296 end;return i(d,l)end;local h,r
r=function(d,l)return a(d%4294967296/2^l)end
h=function(d,l)return(d*2^l)%4294967296 end;return{bnot=bit.bnot,band=n,bor=bit.bor,bxor=s,rshift=r,lshift=h}end)
gf=e(function()local a=bit.bxor;local o=bit.lshift;local i=0x100;local n=0xff;local s=0x11b;local h={}local r={}local function d(p,v)
return a(p,v)end;local function l(p,v)return a(p,v)end;local function u(p)if(p==1)then return 1 end
local v=n-r[p]return h[v]end
local function c(p,v)
if(p==0 or v==0)then return 0 end;local b=r[p]+r[v]if(b>=n)then b=b-n end;return h[b]end
local function m(p,v)if(p==0)then return 0 end;local b=r[p]-r[v]if(b<0)then b=b+n end;return h[b]end
local function f()for p=1,i do print("log(",p-1,")=",r[p-1])end end
local function w()for p=1,i do print("exp(",p-1,")=",h[p-1])end end;local function y()local p=1
for v=0,n-1 do h[v]=p;r[p]=v;p=a(o(p,1),p)if p>n then p=l(p,s)end end end;y()return
{add=d,sub=l,invert=u,mul=c,div=dib,printLog=f,printExp=w}end)
util=e(function()local a=bit.bxor;local o=bit.rshift;local i=bit.band;local n=bit.lshift;local s
local function h(x)
x=a(x,o(x,4))x=a(x,o(x,2))x=a(x,o(x,1))return i(x,1)end;local function r(x,z)
if(z==0)then return i(x,0xff)else return i(o(x,z*8),0xff)end end
local function d(x,z)if(z==0)then return i(x,0xff)else return
n(i(x,0xff),z*8)end end
local function l(x,z,_)local E={}
for T=0,_-1 do
E[T]=
d(x[z+ (T*4)],3)+d(x[z+ (T*4)+1],2)+d(x[z+ (T*4)+2],1)+
d(x[z+ (T*4)+3],0)if _%10000 ==0 then s()end end;return E end;local function u(x,z,_,E)E=E or#x;for T=0,E do
for A=0,3 do z[_+T*4+ (3-A)]=r(x[T],A)end;if E%10000 ==0 then s()end end
return z end;local function c(x)local z=""
for _,E in
ipairs(x)do z=z..string.format("%02x ",E)end;return z end
local function m(x)local z=type(x)
if
(z=="number")then return string.format("%08x",x)elseif(z=="table")then return c(x)elseif
(z=="string")then local _={string.byte(x,1,#x)}return c(_)else return x end end
local function f(x)local z=#x;local _=math.random(0,255)local E=math.random(0,255)
local T=string.char(_,E,_,E,r(z,3),r(z,2),r(z,1),r(z,0))x=T..x;local A=math.ceil(#x/16)*16-#x;local O=""for I=1,A do O=O..
string.char(math.random(0,255))end;return x..O end
local function w(x)local z={string.byte(x,1,4)}if
(z[1]==z[3]and z[2]==z[4])then return true end;return false end
local function y(x)if(not w(x))then return nil end
local z=
d(string.byte(x,5),3)+
d(string.byte(x,6),2)+d(string.byte(x,7),1)+d(string.byte(x,8),0)return string.sub(x,9,8+z)end;local function p(x,z)for _=1,16 do x[_]=a(x[_],z[_])end end
local v,b,g=os.queueEvent,coroutine.yield,os.time;local k=g()local function s()local x=g()
if x-k>=0.03 then k=x;v("sleep")b("sleep")end end
local function q(x)
local z,_,E,T=string.char,math.random,s,table.insert;local A={}
for O=1,x do T(A,_(0,255))if O%10240 ==0 then E()end end;return A end
local function j(x)local z,_,E,T=string.char,math.random,s,table.insert;local A={}for O=1,x do
T(A,z(_(0,255)))if O%10240 ==0 then E()end end
return table.concat(A)end
return
{byteParity=h,getByte=r,putByte=d,bytesToInts=l,intsToBytes=u,bytesToHex=c,toHexString=m,padByteString=f,properlyDecrypted=w,unpadByteString=y,xorIV=p,sleepCheckIn=s,getRandomData=q,getRandomString=j}end)
aes=e(function()local a=util.putByte;local o=util.getByte;local i='rounds'local n="type"local s=1;local h=2
local r={}local d={}local l={}local u={}local c={}local m={}local f={}local w={}local y={}local p={}
local v={0x01000000,0x02000000,0x04000000,0x08000000,0x10000000,0x20000000,0x40000000,0x80000000,0x1b000000,0x36000000,0x6c000000,0xd8000000,0xab000000,0x4d000000,0x9a000000,0x2f000000}
local function b(D)mask=0xf8;result=0
for L=1,8 do result=bit.lshift(result,1)
parity=util.byteParity(bit.band(D,mask))result=result+parity;lastbit=bit.band(mask,1)
mask=bit.band(bit.rshift(mask,1),0xff)if(lastbit~=0)then mask=bit.bor(mask,0x80)else
mask=bit.band(mask,0x7f)end end;return bit.bxor(result,0x63)end;local function g()
for D=0,255 do if(D~=0)then inverse=gf.invert(D)else inverse=D end
mapped=b(inverse)r[D]=mapped;d[mapped]=D end end
local function k()
for D=0,255 do
byte=r[D]
l[D]=
a(gf.mul(0x03,byte),0)+a(byte,1)+a(byte,2)+a(gf.mul(0x02,byte),3)
u[D]=
a(byte,0)+a(byte,1)+a(gf.mul(0x02,byte),2)+a(gf.mul(0x03,byte),3)
c[D]=a(byte,0)+a(gf.mul(0x02,byte),1)+
a(gf.mul(0x03,byte),2)+a(byte,3)
m[D]=
a(gf.mul(0x02,byte),0)+a(gf.mul(0x03,byte),1)+a(byte,2)+a(byte,3)end end
local function q()
for D=0,255 do byte=d[D]
f[D]=
a(gf.mul(0x0b,byte),0)+a(gf.mul(0x0d,byte),1)+a(gf.mul(0x09,byte),2)+
a(gf.mul(0x0e,byte),3)
w[D]=
a(gf.mul(0x0d,byte),0)+a(gf.mul(0x09,byte),1)+a(gf.mul(0x0e,byte),2)+
a(gf.mul(0x0b,byte),3)
y[D]=
a(gf.mul(0x09,byte),0)+a(gf.mul(0x0e,byte),1)+a(gf.mul(0x0b,byte),2)+
a(gf.mul(0x0d,byte),3)
p[D]=
a(gf.mul(0x0e,byte),0)+a(gf.mul(0x0b,byte),1)+a(gf.mul(0x0d,byte),2)+
a(gf.mul(0x09,byte),3)end end;local function j(D)local L=bit.band(D,0xff000000)return
(bit.lshift(D,8)+bit.rshift(L,24))end
local function x(D)return
a(r[o(D,0)],0)+a(r[o(D,1)],1)+a(r[o(D,2)],2)+
a(r[o(D,3)],3)end
local function z(D)local L={}local U=math.floor(#D/4)if(
(U~=4 and U~=6 and U~=8)or(U*4 ~=#D))then
print("Invalid key size: ",U)return nil end;L[i]=U+6;L[n]=s;for C=0,U-1 do
L[C]=
a(D[
C*4+1],3)+a(D[C*4+2],2)+a(D[C*4+3],1)+a(D[C*4+4],0)end
for C=U,(L[i]+1)*4-1 do
local M=L[C-1]
if(C%U==0)then M=j(M)M=x(M)local F=math.floor(C/U)
M=bit.bxor(M,v[F])elseif(U>6 and C%U==4)then M=x(M)end;L[C]=bit.bxor(L[(C-U)],M)end;return L end
local function _(D)local L=o(D,3)local U=o(D,2)local C=o(D,1)local M=o(D,0)
return
a(gf.add(gf.add(gf.add(gf.mul(0x0b,U),gf.mul(0x0d,C)),gf.mul(0x09,M)),gf.mul(0x0e,L)),3)+
a(gf.add(gf.add(gf.add(gf.mul(0x0b,C),gf.mul(0x0d,M)),gf.mul(0x09,L)),gf.mul(0x0e,U)),2)+
a(gf.add(gf.add(gf.add(gf.mul(0x0b,M),gf.mul(0x0d,L)),gf.mul(0x09,U)),gf.mul(0x0e,C)),1)+
a(gf.add(gf.add(gf.add(gf.mul(0x0b,L),gf.mul(0x0d,U)),gf.mul(0x09,C)),gf.mul(0x0e,M)),0)end
local function E(D)local L=o(D,3)local U=o(D,2)local C=o(D,1)local M=o(D,0)local F=bit.bxor(M,C)
local W=bit.bxor(U,L)local Y=bit.bxor(F,W)Y=bit.bxor(Y,gf.mul(0x08,Y))
w=bit.bxor(Y,gf.mul(0x04,bit.bxor(C,L)))
Y=bit.bxor(Y,gf.mul(0x04,bit.bxor(M,U)))
return
a(bit.bxor(bit.bxor(M,Y),gf.mul(0x02,bit.bxor(L,M))),0)+a(bit.bxor(bit.bxor(C,w),gf.mul(0x02,F)),1)+
a(bit.bxor(bit.bxor(U,Y),gf.mul(0x02,bit.bxor(L,M))),2)+a(bit.bxor(bit.bxor(L,w),gf.mul(0x02,W)),3)end
local function T(D)local L=z(D)if(L==nil)then return nil end;L[n]=h;for U=4,(L[i]+1)*4-5 do
L[U]=_(L[U])end;return L end
local function A(D,L,U)for C=0,3 do D[C]=bit.bxor(D[C],L[U*4+C])end end
local function O(D,L)
L[0]=bit.bxor(bit.bxor(bit.bxor(l[o(D[0],3)],u[o(D[1],2)]),c[o(D[2],1)]),m[o(D[3],0)])
L[1]=bit.bxor(bit.bxor(bit.bxor(l[o(D[1],3)],u[o(D[2],2)]),c[o(D[3],1)]),m[o(D[0],0)])
L[2]=bit.bxor(bit.bxor(bit.bxor(l[o(D[2],3)],u[o(D[3],2)]),c[o(D[0],1)]),m[o(D[1],0)])
L[3]=bit.bxor(bit.bxor(bit.bxor(l[o(D[3],3)],u[o(D[0],2)]),c[o(D[1],1)]),m[o(D[2],0)])end
local function I(D,L)
L[0]=a(r[o(D[0],3)],3)+a(r[o(D[1],2)],2)+
a(r[o(D[2],1)],1)+a(r[o(D[3],0)],0)
L[1]=a(r[o(D[1],3)],3)+a(r[o(D[2],2)],2)+
a(r[o(D[3],1)],1)+a(r[o(D[0],0)],0)
L[2]=a(r[o(D[2],3)],3)+a(r[o(D[3],2)],2)+
a(r[o(D[0],1)],1)+a(r[o(D[1],0)],0)
L[3]=a(r[o(D[3],3)],3)+a(r[o(D[0],2)],2)+
a(r[o(D[1],1)],1)+a(r[o(D[2],0)],0)end
local function N(D,L)
L[0]=bit.bxor(bit.bxor(bit.bxor(f[o(D[0],3)],w[o(D[3],2)]),y[o(D[2],1)]),p[o(D[1],0)])
L[1]=bit.bxor(bit.bxor(bit.bxor(f[o(D[1],3)],w[o(D[0],2)]),y[o(D[3],1)]),p[o(D[2],0)])
L[2]=bit.bxor(bit.bxor(bit.bxor(f[o(D[2],3)],w[o(D[1],2)]),y[o(D[0],1)]),p[o(D[3],0)])
L[3]=bit.bxor(bit.bxor(bit.bxor(f[o(D[3],3)],w[o(D[2],2)]),y[o(D[1],1)]),p[o(D[0],0)])end
local function S(D,L)
L[0]=a(d[o(D[0],3)],3)+a(d[o(D[3],2)],2)+
a(d[o(D[2],1)],1)+a(d[o(D[1],0)],0)
L[1]=a(d[o(D[1],3)],3)+a(d[o(D[0],2)],2)+
a(d[o(D[3],1)],1)+a(d[o(D[2],0)],0)
L[2]=a(d[o(D[2],3)],3)+a(d[o(D[1],2)],2)+
a(d[o(D[0],1)],1)+a(d[o(D[3],0)],0)
L[3]=a(d[o(D[3],3)],3)+a(d[o(D[2],2)],2)+
a(d[o(D[1],1)],1)+a(d[o(D[0],0)],0)end
local function H(D,L,U,C,M)U=U or 1;C=C or{}M=M or 1;local F={}local W={}if(D[n]~=s)then
print("No encryption key: ",D[n])return end;F=util.bytesToInts(L,U,4)
A(F,D,0)local Y=util.sleepCheckIn;local P=1;while(P<D[i]-1)do O(F,W)A(W,D,P)P=P+1;O(W,F)
A(F,D,P)P=P+1 end;Y()O(F,W)A(W,D,P)P=P+1;I(W,F)
A(F,D,P)return util.intsToBytes(F,C,M)end
local function R(D,L,U,C,M)U=U or 1;C=C or{}M=M or 1;local F={}local W={}if(D[n]~=h)then
print("No decryption key: ",D[n])return end;F=util.bytesToInts(L,U,4)
A(F,D,D[i])local Y=util.sleepCheckIn;local P=D[i]-1;while(P>2)do N(F,W)A(W,D,P)P=P-1;N(W,F)
A(F,D,P)P=P-1;if P%32 ==0 then Y()end end;Y()
N(F,W)A(W,D,P)P=P-1;S(W,F)A(F,D,P)return util.intsToBytes(F,C,M)end;g()k()q()
return{ROUNDS=i,KEY_TYPE=n,ENCRYPTION_KEY=s,DECRYPTION_KEY=h,expandEncryptionKey=z,expandDecryptionKey=T,encrypt=H,decrypt=R}end)
buffer=e(function()local function a()return{}end;local function o(n,h)table.insert(n,h)
for s=#n-1,1,-1 do if
#n[s]>#n[s+1]then break end;n[s]=n[s]..table.remove(n)end end
local function i(n)for s=#n-1,1,-1 do n[s]=n[s]..
table.remove(n)end;return n[1]end;return{new=a,addString=o,toString=i}end)
ciphermode=e(function()local a={}
function a.encryptString(o,i,n)
local s=iv or{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}local h=aes.expandEncryptionKey(o)local r=buffer.new()for d=1,#i/16 do local l=
(d-1)*16+1;local u={string.byte(i,l,l+15)}
n(h,u,s)
buffer.addString(r,string.char(unpack(u)))end;return
buffer.toString(r)end;function a.encryptECB(o,i,n)aes.encrypt(o,i,1,i,1)end
function a.encryptCBC(o,i,n)
util.xorIV(i,n)aes.encrypt(o,i,1,i,1)for s=1,16 do n[s]=i[s]end end
function a.encryptOFB(o,i,n)aes.encrypt(o,n,1,n,1)util.xorIV(i,n)end;function a.encryptCFB(o,i,n)aes.encrypt(o,n,1,n,1)util.xorIV(i,n)
for s=1,16 do n[s]=i[s]end end
function a.decryptString(o,i,n)local s=iv or
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}local h
if(n==a.decryptOFB or
n==a.decryptCFB)then
h=aes.expandEncryptionKey(o)else h=aes.expandDecryptionKey(o)end;local r=buffer.new()for d=1,#i/16 do local l=(d-1)*16+1
local u={string.byte(i,l,l+15)}s=n(h,u,s)
buffer.addString(r,string.char(unpack(u)))end;return
buffer.toString(r)end;function a.decryptECB(o,i,n)aes.decrypt(o,i,1,i,1)return n end;function a.decryptCBC(o,i,n)
local s={}for h=1,16 do s[h]=i[h]end;aes.decrypt(o,i,1,i,1)
util.xorIV(i,n)return s end;function a.decryptOFB(o,i,n)
aes.encrypt(o,n,1,n,1)util.xorIV(i,n)return n end;function a.decryptCFB(o,i,n)
local s={}for h=1,16 do s[h]=i[h]end;aes.encrypt(o,n,1,n,1)
util.xorIV(i,n)return s end;return a end)AES128=16;AES192=24;AES256=32;ECBMODE=1;CBCMODE=2;OFBMODE=3;CFBMODE=4
local function t(a,o)local i=o;if
(o==AES192)then i=32 end
if(i>#a)then local s=""
for h=1,i-#a do s=s..string.char(0)end;a=a..s else a=string.sub(a,1,i)end;local n={string.byte(a,1,#a)}
a=ciphermode.encryptString(n,a,ciphermode.encryptCBC)a=string.sub(a,1,o)return{string.byte(a,1,#a)}end
function encrypt(a,o,i,n)assert(a~=nil,"Empty password.")
assert(a~=nil,"Empty data.")local n=n or CBCMODE;local i=i or AES128;local s=t(a,i)
local h=util.padByteString(o)
if(n==ECBMODE)then
return ciphermode.encryptString(s,h,ciphermode.encryptECB)elseif(n==CBCMODE)then
return ciphermode.encryptString(s,h,ciphermode.encryptCBC)elseif(n==OFBMODE)then
return ciphermode.encryptString(s,h,ciphermode.encryptOFB)elseif(n==CFBMODE)then
return ciphermode.encryptString(s,h,ciphermode.encryptCFB)else return nil end end
function decrypt(a,o,i,n)local n=n or CBCMODE;local i=i or AES128;local s=t(a,i)local h
if(n==ECBMODE)then
h=ciphermode.decryptString(s,o,ciphermode.decryptECB)elseif(n==CBCMODE)then
h=ciphermode.decryptString(s,o,ciphermode.decryptCBC)elseif(n==OFBMODE)then
h=ciphermode.decryptString(s,o,ciphermode.decryptOFB)elseif(n==CFBMODE)then
h=ciphermode.decryptString(s,o,ciphermode.decryptCFB)end;result=util.unpadByteString(h)
if(result==nil)then return nil end;return result end;return{}
----------------------------------------------------------------------
The aeslua (all versions) is provided under the terms and
conditions of the GNU Lesser General Public Library, which is stated
below. It can also be found at:
http://www.gnu.org/copyleft/lesser.html
----------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence the
version number 2.1.]
Preamble
The licenses for most software are designed to take away your freedom to
share and change it. By contrast, the GNU General Public Licenses are
intended to guarantee your freedom to share and change free software--to
make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the Free
Software Foundation and other authors who decide to use it. You can use
it too, but we suggest you first think carefully about whether this
license or the ordinary General Public License is the better strategy to
use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish); that you receive source code or can get it if
you want it; that you can change the software and use pieces of it in
new free programs; and that you are informed that you can do these
things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for you
if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis or
for a fee, you must give the recipients all the rights that we gave you.
You must make sure that they, too, receive or can get the source code.
If you link other code with the library, you must provide complete
object files to the recipients, so that they can relink them with the
library after making changes to the library and recompiling it. And you
must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that there is
no warranty for the free library. Also, if the library is modified by
someone else and passed on, the recipients should know that what they
have is not the original version, so that the original author's
reputation will not be affected by problems that might be introduced by
others.
Finally, software patents pose a constant threat to the existence of any
free program. We wish to make sure that a company cannot effectively
restrict the users of a free program by obtaining a restrictive license
from a patent holder. Therefore, we insist that any patent license
obtained for a version of the library must be consistent with the full
freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the ordinary
GNU General Public License. This license, the GNU Lesser General Public
License, applies to certain designated libraries, and is quite different
from the ordinary General Public License. We use this license for
certain libraries in order to permit linking those libraries into
non-free programs.
When a program is linked with a library, whether statically or using a
shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the entire
combination fits its criteria of freedom. The Lesser General Public
License permits more lax criteria for linking other code with the
library.
We call this license the "Lesser" General Public License because it does
Less to protect the user's freedom than the ordinary General Public
License. It also provides other free software developers Less of an
advantage over competing non-free programs. These disadvantages are the
reason we use the ordinary General Public License for many libraries.
However, the Lesser license provides advantages in certain special
circumstances.
For example, on rare occasions, there may be a special need to encourage
the widest possible use of a certain library, so that it becomes a
de-facto standard. To achieve this, non-free programs must be allowed to
use the library. A more frequent case is that a free library does the
same job as widely used non-free libraries. In this case, there is
little to gain by limiting the free library to free software only, so we
use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of free
software. For example, permission to use the GNU C Library in non-free
programs enables many more people to use the whole GNU operating system,
as well as its variant, the GNU/Linux operating system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is linked
with the Library has the freedom and the wherewithal to run that program
using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or other
authorized party saying it may be distributed under the terms of this
Lesser General Public License (also called "this License"). Each
licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work which
has been distributed under these terms. A "work based on the Library"
means either the Library or any derivative work under copyright law:
that is to say, a work containing the Library or a portion of it, either
verbatim or with modifications and/or translated straightforwardly into
another language. (Hereinafter, translation is included without
limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for making
modifications to it. For a library, complete source code means all the
source code for all modules it contains, plus any associated interface
definition files, plus the scripts used to control compilation and
installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of running
a program using the Library is not restricted, and output from such a
program is covered only if its contents constitute a work based on the
Library (independent of the use of the Library in a tool for writing
it). Whether that is true depends on what the Library does and what the
program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's complete
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the notices
that refer to this License and to the absence of any warranty; and
distribute a copy of this License along with the Library.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Library or any portion of
it, thus forming a work based on the Library, and copy and distribute
such modifications or work under the terms of Section 1 above, provided
that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the application.
Therefore, Subsection 2d requires that any application-supplied function
or table used by this function must be optional: if the application does
not supply it, the square root function must still compute square
roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library, and
can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based on
the Library, the distribution of the whole must be on the terms of this
License, whose permissions for other licensees extend to the entire
whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or
contest your rights to work written entirely by you; rather, the intent
is to exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the
Library with the Library (or with a work based on the Library) on a
volume of a storage or distribution medium does not bring the other work
under the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so that
they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in these
notices.
Once this change is made in a given copy, it is irreversible for that
copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of the
Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or derivative
of it, under Section 2) in object code or executable form under the
terms of Sections 1 and 2 above provided that you accompany it with the
complete corresponding machine-readable source code, which must be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange.
If distribution of object code is made by offering access to copy from a
designated place, then offering equivalent access to copy the source
code from the same place satisfies the requirement to distribute the
source code, even though third parties are not compelled to copy the
source along with the object code.
5. A program that contains no derivative of any portion of the Library,
but is designed to work with the Library by being compiled or linked
with it, is called a "work that uses the Library". Such a work, in
isolation, is not a derivative work of the Library, and therefore falls
outside the scope of this License.
However, linking a "work that uses the Library" with the Library creates
an executable that is a derivative of the Library (because it contains
portions of the Library), rather than a "work that uses the library".
The executable is therefore covered by this License. Section 6 states
terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be linked
without the Library, or if the work is itself a library. The threshold
for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data structure
layouts and accessors, and small macros and small inline functions (ten
lines or less in length), then the use of the object file is
unrestricted, regardless of whether it is legally a derivative work.
(Executables containing this object code plus portions of the Library
will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6, whether
or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or link a
"work that uses the Library" with the Library to produce a work
containing portions of the Library, and distribute that work under terms
of your choice, provided that the terms permit modification of the work
for the customer's own use and reverse engineering for debugging such
modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work during
execution displays copyright notices, you must include the copyright
notice for the Library among them, as well as a reference directing the
user to the copy of this License. Also, you must do one of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood that
the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at least
three years, to give the same user the materials specified in
Subsection 6a, above, for a charge no more than the cost of
performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the Library"
must include any data and utility programs needed for reproducing the
executable from it. However, as a special exception, the materials to be
distributed need not include anything that is normally distributed (in
either source or binary form) with the major components (compiler,
kernel, and so on) of the operating system on which the executable runs,
unless that component itself accompanies the executable.
It may happen that this requirement contradicts the license restrictions
of other proprietary libraries that do not normally accompany the
operating system. Such a contradiction means you cannot use both them
and the Library together in an executable that you distribute.
7. You may place library facilities that are a work based on the Library
side-by-side in a single library together with other library facilities
not covered by this License, and distribute such a combined library,
provided that the separate distribution of the work based on the Library
and of the other library facilities is otherwise permitted, and provided
that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute the
Library except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense, link with, or distribute the
Library is void, and will automatically terminate your rights under this
License. However, parties who have received copies, or rights, from you
under this License will not have their licenses terminated so long as
such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and all
its terms and conditions for copying, distributing or modifying the
Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot distribute
so as to satisfy simultaneously your obligations under this License and
any other pertinent obligations, then as a consequence you may not
distribute the Library at all. For example, if a patent license would
not permit royalty-free redistribution of the Library by all those who
receive copies directly or indirectly through you, then the only way you
could satisfy both it and this License would be to refrain entirely from
distribution of the Library.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply, and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is implemented
by public license practices. Many people have made generous
contributions to the wide range of software distributed through that
system in reliance on consistent application of that system; it is up to
the author/donor to decide if he or she is willing to distribute
software through any other system and a licensee cannot impose that
choice.
This section is intended to make thoroughly clear what is believed to be
a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may
add an explicit geographical distribution limitation excluding those
countries, so that distribution is permitted only in or among countries
not thus excluded. In such case, this License incorporates the
limitation as if written in the body of this License.
13. The Free Software Foundation may publish revised and/or new versions
of the Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a license
version number, you may choose any version ever published by the Free
Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free Software
Foundation; we sometimes make exceptions for this. Our decision will be
guided by the two goals of preserving the free status of all derivatives
of our free software and of promoting the sharing and reuse of software
generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH
YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY
(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR
OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
@Commandcracker
Copy link
Author

Commandcracker commented Jul 6, 2022

Other Pure Lua aes implementations:
KillaVanilla's aes.lua for ComputerCraft an mod for Minecraft
idiomic's aes.lua
bighil's aes.lua SquidDev's aes.lua is based on it

SquidDev's post about his aes.lua: http://www.computercraft.info/forums2/index.php?/topic/18930-aes-encryption/
KillaVanilla's post about his aes.lua: http://www.computercraft.info/forums2/index.php?/topic/12450-killavanillas-various-apis/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment