Advertisement
pepeknamornik

P7_crypt

Apr 1st, 2023 (edited)
1,207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.02 KB | None | 0 0
  1. verze = "23.0401.R1"
  2. local args = {...}
  3.  
  4. if #args < 2 then
  5.   print("Usage: lua encrypt.lua <key> <file> [remove_original]")
  6.   return
  7. end
  8.  
  9. local key = args[1]
  10. local input_file = args[2]
  11. local remove_original = args[3] == "true"
  12.  
  13. -- check if file is encrypted
  14. local is_encrypted = input_file:sub(-4) == ".pcr"
  15.  
  16. -- read input file
  17. local file = io.open(input_file, "rb")
  18. if not file then
  19.   print("Error: Input file not found")
  20.   return
  21. end
  22. local input_data = file:read("*all")
  23. file:close()
  24.  
  25. -- encryption function
  26. local function encrypt(text, key)
  27.   local result = ""
  28.   for i = 1, #text do
  29.     local byte = text:byte(i)
  30.     local key_byte = key:byte((i - 1) % #key + 1)
  31.     result = result .. string.char(bit.bxor(byte, key_byte))
  32.   end
  33.   return result
  34. end
  35.  
  36. -- decryption function
  37. local function decrypt(ciphertext, key)
  38.   return encrypt(ciphertext, key) -- decryption is just encryption with the same key
  39. end
  40.  
  41. -- encrypt or decrypt data
  42. local output_data
  43. local output_file
  44. if is_encrypted then
  45.   -- decrypt data
  46.   output_data = decrypt(input_data, key)
  47.   output_file = input_file:sub(1, -5)
  48. else
  49.   -- encrypt data
  50.   output_data = encrypt(input_data, key)
  51.   output_file = input_file .. ".pcr"
  52. end
  53.  
  54. -- write output file
  55. local file = io.open(output_file, "wb")
  56. if not file then
  57.   return
  58. end
  59. file:write(output_data)
  60. file:close()
  61.  
  62. -- check if output file was created
  63. if not fs.exists(output_file) then
  64.   return
  65. end
  66.  
  67. -- remove original file if specified
  68. if remove_original then
  69.   local success, message = fs.delete(input_file)
  70.   if not success then
  71.     return
  72.   end
  73.  
  74.   -- rename new file
  75.   success, message = fs.move(output_file, input_file)
  76.   if not success then
  77.     return
  78.   end
  79. else
  80.   -- rename new file
  81.   success, message = fs.move(output_file, input_file .. ".new")
  82.   if not success then
  83.     return
  84.   end
  85. end
  86.  
  87. -- output success message
  88. if is_encrypted then
  89.   print("File decrypted and saved as " .. output_file)
  90. else
  91.   print("File encrypted and saved as " .. output_file)
  92. end
  93.  
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement