t8rt0t

encryptionAPI.lua

Apr 12th, 2024 (edited)
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 13.05 KB | None | 0 0
  1. if not screen then os.loadAPI("apis/screen.lua") end
  2. magicNumbers = string.char(0x83,0xf9)
  3.  
  4. --Opens some sort of file explorer
  5. --@OptionalArg string path: The path to start from
  6. --@Returns string result: The selected file
  7. --@Returns boolean false: If the path didnt exist, or if the user clicked the "quit" button
  8. function selectFile(path)
  9.     if path and not fs.exists(path) then return false end
  10.     if path and not fs.isDir(path) then return path end
  11.     path = path or "/"
  12.     local files = fs.list(path)
  13.     local items = {}
  14.     for k,v in pairs(files) do
  15.         local color = colors.green
  16.         if not fs.isDir(fs.combine(path,v)) then
  17.             color = colors.white
  18.         end
  19.         local args = screen.section_char .. textutils.serialiseJSON({color=colors.black,bgColor=color}) .. screen.section_char
  20.         table.insert(items,args .. v)
  21.     end
  22.     local selectionScreen = screen.SelectionScreen(1,1,nil,nil,items,"Current dir: "..path)
  23.     local t,data = selectionScreen:selectItem()
  24.     selectionScreen:render(false)
  25.     term.clear()
  26.     if t == "back" then data = ".." end
  27.     if t == "quit" then return false end
  28.     return selectFile(fs.combine(path,data))
  29. end
  30. --Allows a user to type in a password without people watching them
  31. --@OptionalArg number x: The x position to start from
  32. --@OptionalArg number y: The y position to start from
  33. --@OptionalArg number maxLength: The maximum length that the password can be
  34. --@Returns string pass: The password
  35. function enterPassword(x,y,maxLength)
  36.     x = math.max(tonumber(x) or 1,1)
  37.     y = math.max(tonumber(y) or 1,1)
  38.     maxLength = tonumber(maxLength) or 69420
  39.     maxLength = math.max(maxLength,#"Please enter the password:")
  40.     local current = term.current()
  41.     local maxX,maxY = term.getSize()
  42.     local oldx,oldy = term.getCursorPos()
  43.     local oldColor,oldBG = term.getTextColor(), term.getBackgroundColor()
  44.     local wndw = window.create(current,x,y,math.min(maxX,maxLength),2)
  45.     term.redirect(wndw)
  46.     term.clear()
  47.     local pass = ""
  48.     term.setCursorPos(1,1)
  49.     term.setTextColor(colors.white)
  50.     print("Please enter the password:")
  51.     term.write("> ")
  52.     term.setTextColor(colors.red)
  53.     local _,key = os.pullEvent("key")
  54.     while key ~= keys.enter do
  55.         if key <= 256 and #pass <= maxLength then
  56.             local _,char = os.pullEvent("char")
  57.             pass = pass .. char
  58.             term.write("*")
  59.         elseif key == keys.delete or key == keys.backspace then
  60.             pass = string.sub(pass,1,-2)
  61.             term.clear()
  62.             term.setCursorPos(1,1)
  63.             term.setTextColor(colors.white)
  64.             print("Please enter the password:")
  65.             term.write("> ")
  66.             term.setTextColor(colors.red)
  67.             term.write(string.gsub(pass,".","*"))
  68.         end
  69.         _,key = os.pullEvent("key")
  70.     end
  71.     wndw.setVisible(false)
  72.     term.redirect(current)
  73.     term.setCursorPos(oldx,oldy)
  74.     term.setTextColor(oldColor)
  75.     term.setBackgroundColor(oldBG)
  76.     return pass
  77. end
  78.  
  79. --Turns a string into a number
  80. --@Arg string str: The string to hash
  81. --@OptionalArg number size: The range of the hash, from 0 to size-1. Defaults to 256 (making the hash a byte)
  82. --@Returns number hash: The resultant hash
  83. local function getHash(str,size)
  84.     size = tonumber(size) or 256
  85.     local hash = 0
  86.     math.randomseed(size)
  87.     for i=1,#str do
  88.         math.randomseed(string.byte(str,i) + math.random(size))
  89.         hash = (hash + math.random(size))%size
  90.     end
  91.     return hash%size
  92. end
  93.  
  94. --Scrambles a string
  95. --@Arg string str: The string to scramble
  96. --@Arg string pass: The pass to use to scramble
  97. --@OptionalArg number epoch: Additional random factor to add to the scramble
  98. --@Returns string result, table ops: The scrambled string, and the operations
  99. local function scramble(str,pass,epoch)
  100.     if #str == 0 then return "" end
  101.     local numOps = math.floor(#str*1.5) + getHash(pass,#str + 69)
  102.     local ops = {}
  103.     local res = str
  104.     math.randomseed(getHash(pass,256^2)/numOps + (tonumber(epoch) or 0))
  105.     for i=1,numOps do
  106.         op1,op2 = math.random(#str),math.random(#str)
  107.         local char1 = string.sub(res,op1,op1)
  108.         local char2 = string.sub(res,op2,op2)
  109.         res = string.sub(res,1,op2-1) .. char1 .. string.sub(res,op2+1)
  110.         res = string.sub(res,1,op1-1)..char2 .. string.sub(res,op1+1)
  111.         table.insert(ops,{op1,op2})
  112.     end
  113.     return res,ops
  114. end
  115. --Unscrambles a string
  116. --@Arg string str: The string to unscramble
  117. --@Arg string pass: the pass to use to unscramble
  118. --@OptionalArg number epoch:
  119. local function unscramble(str,pass,epoch)
  120.     local _,ops = scramble(str,pass,epoch)
  121.     local res = str
  122.     for i=#ops,1,-1 do
  123.         local char1 = string.sub(res,ops[i][2],ops[i][2])
  124.         local char2 = string.sub(res,ops[i][1],ops[i][1])
  125.         res = string.sub(res,1,ops[i][1] - 1) .. char1 .. string.sub(res, ops[i][1] + 1, -1)
  126.         res = string.sub(res,1,ops[i][2] - 1) .. char2 .. string.sub(res, ops[i][2] + 1, -1)
  127.     end
  128.     return res
  129. end
  130.        
  131. --Encrypts a string using a passphrase
  132. --@Arg string str: The string to encrypt
  133. --@Arg string pass: The passphrase to use to encrypt
  134. --@OptionalArg number hashSize: The maximum number of the hashsize. Make larger for harder to decrypt data. Defaults to 256
  135. --@OptionalArg boolean noPadding: If set to true, will not add padding
  136. --@OptionalArg boolean noScramble: If set to true, will not scramble letters
  137. --@OptionalArg number epoch: Adds an additional epoch factor to the scrambling and encryption
  138. --@Returns string gnirts: The encrypted string
  139. function encryptString(str,pass,hashSize,noPadding,noScramble,epoch)
  140.     epoch = tonumber(epoch) or 0
  141.     local gnirts = {}
  142.     for i=1,#pass do
  143.         gnirts[i] = {}
  144.         math.randomseed(getHash(pass .. string.sub(pass,i,i), hashSize) + epoch)
  145.         for j=1,math.ceil(#str/#pass) do
  146.             local oldChar = string.sub(str,(j-1)*#pass+i,(j-1)*#pass+i)
  147.             if #oldChar > 0 then
  148.                 local char = string.char( (string.byte(oldChar)+math.random(256))%256 )
  149.                 gnirts[i][j] = char
  150.             end
  151.         end
  152.     end
  153.     local result = ""
  154.     for i=1,#gnirts[1] do
  155.         for j=1,#gnirts do
  156.             result = result .. (gnirts[j][i] or "")
  157.         end
  158.     end
  159.     if not noPadding then
  160.         --Attaching padding
  161.         math.randomseed(getHash(pass, hashSize) + epoch)
  162.         local hlen,flen = math.random(256),math.random(256)
  163.         local header,footer = "",""
  164.         math.randomseed(os.epoch())
  165.         for i=1,hlen do
  166.             header = header .. string.char(math.random(256)-1)
  167.         end
  168.         for i=1,flen do
  169.             footer = footer .. string.char(math.random(256)-1)
  170.         end
  171.         result = header .. result .. footer
  172.     end
  173.     if not noScramble then
  174.         result = scramble(result,pass)
  175.     end
  176.     math.randomseed(os.epoch("local"))
  177.     return result
  178. end
  179. --Decrypts the string using a passphrase
  180. --@Arg string str: The string to decrypt
  181. --@Arg string pass: The passphrase to use to decrypt
  182. --@OptionalArg number hashSize: The hashSize of the password
  183. --@OptionalArg boolean noPadding: Whether to ignore padding or not
  184. --@OptionalArg boolean noScramble: Whether to not unscramble the data
  185. --@OptionalArg number epoch: The additional epoch factor to use
  186. --@Returns string result: The decrypted string
  187. function decryptString(str,pass,hashSize,noPadding,noScramble,epoch)
  188.     epoch = tonumber(epoch) or 0
  189.     if not noScramble then
  190.         str = unscramble(str,pass)
  191.     end
  192.     if not noPadding then
  193.         math.randomseed(getHash(pass, hashSize) + epoch)
  194.         local hlen,flen = math.random(256),math.random(256)
  195.         str = string.sub(str,hlen+1,-1*(flen+1)) --popping off headers
  196.     end
  197.     local gnirts = {}
  198.     for i=1,#pass do
  199.         gnirts[i] = {}
  200.         math.randomseed(getHash(pass .. string.sub(pass,i,i), hashSize) + epoch)
  201.         for j=1,math.ceil(#str/#pass) do
  202.             local oldChar = string.sub(str,(j-1)*#pass+i,(j-1)*#pass+i)
  203.             if #oldChar > 0 then
  204.                 local char = string.char( (string.byte(oldChar)-math.random(256))%256 )
  205.                 gnirts[i][j] = char
  206.             end
  207.         end
  208.     end
  209.     local result = ""
  210.     for i=1,#gnirts[1] do
  211.         for j=1,#gnirts do
  212.             result = result .. (gnirts[j][i] or "")
  213.         end
  214.     end
  215.     math.randomseed(os.epoch("local"))
  216.     return result
  217. end
  218. --Encrypts a file using a passcode
  219. --@OptionalArg string path: The file to encrypt. If not given, then it opens up a file explorer
  220. --@OptionalArg string pass: The password used to encrypt. If not given, it opens up a password entry system
  221. --@OptionalArg number hashSize: The size of the hash to use for generating random seeds. Default 256
  222. --@OptionalArg boolean noPadding: Set to true to not add padding
  223. --@OptionalArg boolean noScramble: Set to true to not scramble the file
  224. function encryptFile(path,pass,hashSize,noPadding,noScramble)
  225.     hashSize = math.floor(math.max(0,math.min(256*256,tonumber(hashSize) or 256))) --Ensuring valid integer value
  226.     if not path or not fs.exists(path) then
  227.         local f = selectFile()
  228.         if not f then return end
  229.         path = f
  230.     end
  231.     if not pass then
  232.         local password,confirmPass = "", ""
  233.         repeat
  234.             term.clear()
  235.             password = enterPassword(1,1,16)
  236.             term.setCursorPos(1,3)
  237.             print("Confirm password:")
  238.             confirmPass = enterPassword(1,4,16)
  239.             term.clear()
  240.             if password ~= confirmPass then
  241.                 term.setCursorPos(1,6)
  242.                 print("Passwords do not match!")
  243.             end
  244.         until password == confirmPass and #password >= 1
  245.         pass = password
  246.         term.setCursorPos(1,1)
  247.         term.clear()
  248.     end
  249.     local file = fs.open(path,"r")
  250.     local data = file.readAll()
  251.     file.close()
  252.     local encryptedData = encryptString(data,pass,hashSize,noPadding,noScramble)
  253.     local tempPath = fs.combine("temp/",path)
  254.     local file = fs.open(tempPath,"w+")
  255.     file.write(magicNumbers)
  256.     file.write(string.char(math.floor(hashSize/256)))
  257.     file.write(string.char(hashSize%256))
  258.     local flags = 0
  259.     if noPadding then flags = flags + 1 end
  260.     if noScramble then flags = flags + 2 end
  261.     file.write(string.char(flags))
  262.     file.write(encryptedData)
  263.     file.close()
  264.     fs.delete(path)
  265.     fs.copy(tempPath,path)
  266.     fs.delete("temp")
  267. end
  268. --Decrypts a file
  269. --@OptionalArg string path: the path to decrypt
  270. --@OptionalArg string pass: The password to decrypt with
  271. --@OptionalArg boolean replace: Whether the file should be replaced or not
  272. --@Returns string data, boolean wasEncrypted, string path: The decrypted data, whether it was encrypted or not, and the path
  273. function decryptFile(path,pass,replace)
  274.     if not path or not fs.exists(path) then
  275.         local f = selectFile()
  276.         if not f then return end
  277.         path = f
  278.     end
  279.     if not pass then
  280.         local password,confirmPass = "", ""
  281.         repeat
  282.             term.clear()
  283.             password = enterPassword(1,1,16)
  284.             term.setCursorPos(1,3)
  285.             print("Confirm password:")
  286.             confirmPass = enterPassword(1,4,16)
  287.             term.clear()
  288.             if password ~= confirmPass then
  289.                 term.setCursorPos(1,6)
  290.                 print("Passwords do not match!")
  291.             end
  292.         until password == confirmPass and #password >= 1
  293.         pass = password
  294.         term.setCursorPos(1,1)
  295.         term.clear()
  296.     end
  297.     local file = fs.open(path,"r")
  298.     local data = file.readAll()
  299.     file.close()
  300.     if string.sub(data,1,2) ~= magicNumbers then
  301.         print("Not an encrypted file")
  302.     return data, false, path end
  303.     local hashSize = string.byte(string.sub(data,3,3))
  304.     hashSize = hashSize*256+ string.byte(string.sub(data,4,4))
  305.     local flags = string.byte(string.sub(data,5,5))
  306.     local decryptedData = decryptString(string.sub(data,6,-1),pass,hashSize,flags%2 == 1, math.floor(flags/2)%2 == 1)
  307.     if replace then
  308.         local tempPath = fs.combine("temp/",path)
  309.         local file = fs.open(tempPath,"w+")
  310.         file.write(decryptedData)
  311.         file.close()
  312.         fs.delete(path)
  313.         fs.copy(tempPath,path)
  314.         fs.delete("temp")
  315.     end
  316.     return decryptedData, true, path
  317. end
  318. --Runs an encrypted file
  319. --@OptionalArg string path: The file to run
  320. --@OptionalArg string pass: The password to use to decrypt
  321. --@Args any args: The args to run with the file
  322. function runEncrypted(path,pass,...)
  323.     local args = {...}
  324.     local decryptedData, wasEncrypted, path = decryptFile(path,pass,false)
  325.     if not decryptedData then return end
  326.     if wasEncrypted then
  327.         local tempPath = fs.combine("temp/",path)
  328.         local file = fs.open(tempPath,"w+")
  329.         file.write(decryptedData)
  330.         file.close()
  331.         local success = pcall(function() if not os.run({},tempPath,unpack(args)) then error() end end)
  332.         fs.delete("temp")
  333.         if not success then error() end
  334.     else
  335.         os.run({},path,unpack(args))
  336.     end
  337. end
Advertisement
Add Comment
Please, Sign In to add comment