Advertisement
HeroBrine1st

Cryptednote.lua

Jul 6th, 2018
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 5.92 KB | None | 0 0
  1. local crypt = require("crypt")
  2. local component = require("component")
  3. local computer = require("computer")
  4. local unicode = require("unicode")
  5. local gpu = component.gpu
  6. local fs = require("filesystem")
  7. local term = require("term")
  8. local event = require("event")
  9. local shell = require("shell")
  10. local dir = "/usr/cryptednote/"
  11. local tmp = {}
  12. local args,options = shell.parse(...)
  13.  
  14. local function parts(str,partLen)
  15.   local i = 1
  16.   local len = unicode.len(str)
  17.   return function()
  18.     if i > len then return nil end
  19.     local part = unicode.sub(str,i,i+partLen-1)
  20.     i = i+partLen
  21.     return part
  22.   end
  23. end
  24.  
  25. local function writeFile(path,data)
  26.   local handle, reason = io.open(path,"w")
  27.   if not handle then return nil, reason end
  28.   for part in parts(data,1024) do
  29.     handle:write(part)
  30.   end
  31.   handle:close()
  32.   return true
  33. end
  34.  
  35. local function readFile(path)
  36.   local handle, reason = io.open(path,"r")
  37.   if not handle then return nil, reason end
  38.   local buffer = ""
  39.   for line in handle:lines() do
  40.     buffer = buffer .. line .. "\n"
  41.   end
  42.   handle:close()
  43.   return buffer
  44. end
  45.  
  46. local function readFileStandart(path)
  47.   local handle, reason = io.open(path,"r")
  48.   if not handle then return nil, reason end
  49.   local buffer = ""
  50.   repeat
  51.     local data,reason = handle:read()
  52.     if data then buffer = buffer .. data end
  53.     if not data and reason then handle:close() return nil, reason end
  54.   until not data
  55.   handle:close()
  56.   return buffer
  57. end
  58.  
  59. local function write(text)
  60.   local _, y = term.getCursor()
  61.   term.setCursor(1,y-1)
  62.   print(text)
  63. end
  64.  
  65. local function encrypt(str,key)
  66.   local crypted = ""
  67.   local i = 0
  68.   local _parts = math.ceil(unicode.len(str)/128)
  69.   for part in parts(str,128) do
  70.     i = i + 1
  71.     crypted = crypted .. crypt.crypt(part,key)
  72.     write("Encrypting in process. Part " .. tostring(i) .. "/" .. tostring(_parts))
  73.     computer.pullSignal(0)
  74.   end
  75.   return crypted
  76. end
  77.  
  78.  
  79.  
  80. local function decrypt(str,key)
  81.   local uncrypted = ""
  82.   local i = 0
  83.   local _parts = math.ceil(#str/256)
  84.   for part in parts(str,256) do
  85.     i = i + 1
  86.     uncrypted = uncrypted .. crypt.decrypt(part,key)
  87.     write("Decrypting in process. Part " .. tostring(i) .. "/" .. tostring(_parts))
  88.     computer.pullSignal(0)
  89.   end
  90.   return uncrypted:gsub("\0","")
  91. end
  92.  
  93.  
  94. local function edit(path,rewrite)
  95.   term.clear()
  96.   if not fs.exists(path) or rewrite then writeFile(path,crypt.crypt("--ваша новая заметка--",tmp.keys)) end
  97.   local tmpname = fs.concat(dir,"temp.crtnt")
  98.   do
  99.     local buffer = readFileStandart(path)
  100.     writeFile(tmpname,decrypt(buffer,tmp.keys))
  101.   end
  102.   os.execute("edit " .. tmpname)
  103.   do
  104.     local buffer1 = readFile(tmpname)
  105.     os.remove(tmpname)
  106.     writeFile(path,encrypt(buffer1,tmp.keys))
  107.   end
  108. end
  109. fs.makeDirectory(dir)
  110.  
  111. if fs.exists(fs.concat(dir,"password.md5")) then
  112.   tmp.md5 = readFileStandart(fs.concat(dir,"password.md5"))
  113. end
  114. local str = "Введите пароль: "
  115. if not tmp.md5 then str = "Введите новый пароль: " end
  116. local crtd = false
  117. while not tmp.keys do
  118.   io.write(str)
  119.   local psk = term.read(_,_,_,"•")
  120.   if not psk then print("Выход") os.exit() end
  121.   print("\nВычисление контрольной суммы...")
  122.   local checksum = crypt.md5(psk)
  123.   write("Вычисление контрольной суммы... Контрольная сумма вычислена")
  124.   if tmp.md5 then
  125.     print("Сравнение контрольных сумм... ")
  126.     if tmp.md5 == crypt.md5(psk) then
  127.       write("Сравнение контрольных сумм...  Пароль верный")
  128.       print("Создание таблицы ключей...")
  129.       tmp.keys = crypt.getkey(psk)
  130.       write("Создание таблицы ключей... Таблица ключей создана")
  131.     else
  132.       write("Сравнение контрольных сумм... Неверный пароль.")
  133.       os.sleep(0.5)
  134.       os.exit()
  135.     end
  136.   else
  137.     print("Форматирование и запись контрольной суммы в файл")
  138.     for file in fs.list(dir) do
  139.       print("Удаление " .. file)
  140.       fs.remove(fs.concat(dir,file))
  141.     end
  142.     tmp.md5 = crypt.md5(psk)
  143.     writeFile(fs.concat(dir,"password.md5"),tmp.md5)
  144.     print("Создание таблицы ключей...")
  145.     tmp.keys = crypt.getkey(psk)
  146.     write("Создание таблицы ключей... Таблица ключей создана.")
  147.     crtd = true
  148.   end
  149.   psk = nil
  150.   os.sleep(0.5)
  151. end
  152. if crtd then
  153.   print("Добро пожаловать в программу cryptednote")
  154.   print("В целях безопасности названия ваших файлов будут защищены хеш-функцией MD5, а их содержимое будет зашифровано паролем, введенном при запуске программы.")
  155.   print("Не передавайте пароль третьим лицам. В случае угрозы безопасности или невозможности ввода пароля удалите файл " .. dir .. "password.md5 , запомнив его содержимое")
  156.   print("Клик для продолжения")
  157.   event.pull("touch")
  158. end
  159. print("Начинается работа с файлом")
  160. if not args[1] then print("Не получено название файла, возврат в консоль.") os.exit() end
  161. local pathmd5 = crypt.md5(args[1])
  162. local path = fs.concat(dir,pathmd5)
  163. if options.execute or options.x then
  164.   local buffer = readFile(path)
  165.   local file = decrypt(buffer,tmp.keys)
  166.   local f, r = load(file)
  167.   if f then
  168.     xpcall(f,function(err)
  169.       print("Error in file: " .. path)
  170.       print("Error code: " .. err)
  171.     end)
  172.   else
  173.     print("Couldn't load file:" .. path)
  174.     print("Error code:" .. r)
  175.   end
  176. else
  177.   edit(path,options.rewrite or options.w)
  178. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement