|
Post by Bit on May 11, 2017 22:49:45 GMT
This one is very simple, yet not as "easy" as my novice series. As always, you are welcome to golf it if you'd like, but not necessary, just like explaining your code. The task: *Make two functions, one to "encrypt" a string, and one to "decrypt" it. *Bonus if you can add a key that needs to be used in order to recover the original string. As always, no hard-coding allowed, and it must work without an internet connection, along with being use-able in any natural circumstance. Also, don't forget to put the language name next to the solution. Has out.
NOTE: Encryption, in this case, means to at least make it unable to recover the original string with basic functions. (Such as :reverse() or :gsub() in Lua.)
|
|
|
Post by AxonMega on May 12, 2017 21:16:24 GMT
Mine is Lua, un-golfed. It randomizes the ids and order of the characters in the given string.
math.randomseed(tick())
local function generateKey(length) --this generates an array with the given length containing numbers in the range of 1 to length local key = {1} for i = 2, length do table.insert(key, math.random(1, #key), i) end return key end
local function encrypt(str, key) local charList = {} for i = 1, #str do table.insert(charList, str:sub(i, i)) end for i, char in ipairs(charList) do charList[i] = string.char(char:byte() + key[i]) end local newList = {} for a, b in ipairs(key) do newList[a] = charList[b] end return table.concat(newList) end
local function decrypt(str, key) local charList = {} for i = 1, #str do table.insert(charList, str:sub(i, i)) end local newList = {} for a, b in ipairs(key) do newList[b] = charList[a] end for i, char in ipairs(newList) do newList[i] = string.char(char:byte() - key[i]) end return table.concat(newList) end
--example:
local str = "This is a secret message!"
local key = generateKey(#str)
local encrypted = encrypt(str, key)
print("Encrypted string:", encrypted)
decrypted = decrypt(encrypted, key)
print("Decrypted string:", decrypted)
|
|
|
Post by Bit on May 12, 2017 22:25:45 GMT
Not bad.
|
|
|
Post by AxonMega on May 12, 2017 22:37:46 GMT
Thank you.
|
|
|
Post by Bit on May 13, 2017 1:01:18 GMT
I'll post my solution later, waiting for more answers.
|
|
|
Post by cntkillme on May 14, 2017 9:45:09 GMT
Here's a fun concept, use RNG for your displacements for each character and the seed as the key. For example:
local function encrypt(str, key) math.randomseed(key) return str:gsub(".", function(char) return string.char((char:byte() + math.random(255)) % 256) end) end
local function decrypt(str, key) math.randomseed(key) return str:gsub(".", function(char) return string.char((char:byte() - math.random(255)) % 256) end) end
|
|