Bacon cipher: Difference between revisions

Content added Content deleted
(Added Kotlin)
No edit summary
Line 536: Line 536:
</pre>
</pre>


=={{header|Lua}}==
<lang Lua>
function Bacon( txt, secret, e )
local alpha = {}, t
function toBits( num, bits )
local t, s = "", 0
for b = bits, 1, -1 do
s = math.fmod( num, 2 )
t = s .. t
num = math.floor( num / 2 )
end
return t
end
function find( a, arr )
for i = 1, #arr do
if arr[i] == a then return i end
end
return -1
end
function toAlpha( secret )
local str, z = "", 0
secret = secret:upper()
for i = 1, string.len( secret ) do
z = secret:sub( i, i )
if z < 'A' or z > 'Z' then
str = str .. alpha[27]
else
k = z:byte( 1 ) - 65 + 1
str = str .. alpha[k]
end
end
return str
end
function fromAlpha( secret )
local l, msg, c, idx = secret:len(), "", 0, 0
if math.fmod( l, 5 ) ~= 0 then
print( "Message length does not match!" )
return
end
for i = 1, l, 5 do
c = secret:sub( i, i + 4 )
idx = find( c, alpha )
if idx > 0 then
if idx == 27 then
msg = msg .. " " -- unknown char - add space
else
msg = msg .. string.char( 64 + idx )
end
end
end
return msg
end
function encode( txt, secret )
local sec, encoded, idx = toAlpha( secret ), "", 0
if sec:len() > txt:len() then
print( "Text is too short!" )
return
end
txt = txt:lower()
for i = 1, string.len( sec ) do
t = txt:sub( idx, idx )
while( t < 'a' or t > 'z' ) do
encoded = encoded .. t
idx = idx + 1
t = txt:sub( idx, idx )
end
idx = idx + 1
if sec:sub( i, i ) == '1' then
encoded = encoded .. string.char( t:byte(1) - 32 )
else
encoded = encoded .. t
end
end
return encoded
end
function decode( txt )
local secret, c = "", 0
for i = 1, string.len( txt ) do
c = txt:sub( i, i )
if not( c < 'a' and ( c < 'A' or c > 'Z' ) or c > 'z' ) then
local s = 0
if c == c:upper() then s = 1 end
secret = secret .. s
end
end
return fromAlpha( secret )
end

-- create alphabet
for i = 0, 26 do
t = ( toBits( i, 5 ) )
alpha[#alpha + 1] = t
end
-- encode or decode
if e == 1 then
return encode( txt, secret )
elseif e == 0 then
return decode( secret )
end
end

local a = Bacon( "one morning, when gregor samsa woke from troubled dreams"..
", he found himself transformed in his bed into a horrible "..
"vermin. he lay on his armour-like back, and if he lifted "..
"his head a little he could see his brown belly, slightly "..
"domed and divided by arches into stiff sections.",
"This is a Bacon cipher test", 1 )
print( a )
print( Bacon( "", a, 0 ) )
</lang>
{{out}}
<pre>
sh-4.3$ lua main.lua
One MOrnING, wHen gRegOr SAmSa wOke fRom TrOUbLed dreaMS, hE found Himself trAnsFORmeD In HIS bEd intO a hOrribLE VErmIN.
He lAy oN his ARMoUr-LikE BacK, anD if He LifTE
THIS IS A BACON CIPHER TEST
</pre>
=={{header|Perl 6}}==
=={{header|Perl 6}}==
Not truly a Bacon Cipher as it doesn't encode using font variations. But fits with the spirit if not the exact definition.
Not truly a Bacon Cipher as it doesn't encode using font variations. But fits with the spirit if not the exact definition.