Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Encryption and Decryption program for ComputerCraft
- -- Encrypts and decrypts every file in the /disk/ directory using a Caesar cipher
- local shift = 3 -- Number of positions to shift each character in the Caesar cipher
- -- Function to encrypt a string using Caesar cipher
- local function encrypt(text, shift)
- local encryptedText = ""
- for i = 1, #text do
- local char = text:sub(i, i)
- local byte = string.byte(char)
- -- Encrypt only printable ASCII characters
- if byte >= 32 and byte <= 126 then
- local newByte = ((byte - 32 + shift) % 95) + 32
- encryptedText = encryptedText .. string.char(newByte)
- else
- encryptedText = encryptedText .. char
- end
- end
- return encryptedText
- end
- -- Function to decrypt a string using Caesar cipher
- local function decrypt(text, shift)
- local decryptedText = ""
- for i = 1, #text do
- local char = text:sub(i, i)
- local byte = string.byte(char)
- -- Decrypt only printable ASCII characters
- if byte >= 32 and byte <= 126 then
- local newByte = ((byte - 32 - shift) % 95) + 32
- decryptedText = decryptedText .. string.char(newByte)
- else
- decryptedText = decryptedText .. char
- end
- end
- return decryptedText
- end
- -- Function to process a file (encrypt or decrypt based on the action)
- local function processFile(filePath, action)
- local file = fs.open(filePath, "r")
- if not file then
- print("Failed to open file: " .. filePath)
- return
- end
- local content = file.readAll()
- file.close()
- local processedContent
- if action == "encrypt" then
- processedContent = encrypt(content, shift)
- elseif action == "decrypt" then
- processedContent = decrypt(content, shift)
- else
- print("Invalid action: " .. action)
- return
- end
- -- Write processed content back to the file
- local processedFile = fs.open(filePath, "w")
- if not processedFile then
- print("Failed to write to file: " .. filePath)
- return
- end
- processedFile.write(processedContent)
- processedFile.close()
- print(action:capitalize() .. ": " .. filePath)
- end
- -- Function to encrypt or decrypt all files in /disk/
- local function processAllFilesInDisk(action)
- local path = "/disk/"
- if not fs.exists(path) then
- print("Path does not exist: " .. path)
- return
- end
- local files = fs.list(path)
- for _, file in ipairs(files) do
- local filePath = fs.combine(path, file)
- if not fs.isDir(filePath) then
- processFile(filePath, action)
- else
- print("Skipping directory: " .. filePath)
- end
- end
- print("All files " .. action .. "ed.")
- end
- -- Helper function to capitalize the first letter of a string
- function string:capitalize()
- return (self:gsub("^%l", string.upper))
- end
- -- Start the process
- local action = "encrypt" -- Change this to "decrypt" to decrypt files
- processAllFilesInDisk(action)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement