Bacon cipher: Difference between revisions

(Added Perl example (partial))
Line 1,452:
signify anything). This example will work with anything in the
ASCII range... even code! $r%_-^&*(){}+~ #=`/\';*1234567890"'</pre>
 
=={{header|Phix}}==
Rather than explictly using 'a'="AAAAA", 'b'='AAAAB', c='AAABA", etc, this
notes that "AAAAA".."BBBAA" are just another form of binary, and therefore
handles them as 0..26, ie a-z plus space for any non-letters.
 
You could of course extend this to encode full binary, by changing the bits
to 8, and accepting every input byte as-is, or use an image file instead of
plaintext simply by reading it using get_text() and (from some appropriate
offset) setting the pixel colours to odd/even instead of upper/lower, and
start by encoding the message length in bytes, that is rather than sending
half of/an obviously corrupt image file.
 
<lang Phix>constant bits = 5,
mask = power(2,bits-1)
 
function bacon(string msg, plaintext)
plaintext = lower(plaintext)
integer ptdx = 0
for i=1 to length(msg) do
integer inch = lower(msg[i])-'a'
if inch<0 or inch>25 then inch = 26 end if
integer m = mask
while true do -- encode one character
while true do -- find an a-z for this bit
ptdx += 1
if ptdx>length(plaintext) then
crash("plaintext too short")
end if
integer ch = plaintext[ptdx]
if ch>='a' and ch<='z' then
if and_bits(inch,m) then
plaintext[ptdx] = upper(ch)
end if
exit
end if
end while
if m=1 then exit end if
m /= 2
end while
end for
return plaintext[1..ptdx]
-- return plaintext -- note: yields ...dogaaaaaaaaaa.....
end function -- [or the "oops?" in nocab()]
 
function nocab(string plaintext)
string res = ""
integer m = mask, ch = 'a'
for i=1 to length(plaintext) do
integer inch = lower(plaintext[i])
if inch>='a' and inch<='z' then
if inch!=plaintext[i] then
ch += m
end if
if m=1 then
res &= iff(ch>'z'?' ':ch)
m = mask
ch = 'a'
else
m /= 2
end if
end if
end for
if m!=mask or ch!='a' then crash("oops?") end if
return res
end function
 
constant plaintext = """
Bacon's cipher is a method of steganography created by Francis Bacon.
This task is to implement a program for encryption and decryption of
plaintext using the simple alphabet of the baconian cipher or other
representation of this alphabet. The baconian alphabet may optionally
be extended to encode all lower case characters individually and/or
add a few punctuation characters such as the space."""
 
constant msg = "The quick brown fox jumps over the lazy dog"
 
string ant = bacon(msg,plaintext),
dec = nocab(ant)
puts(1,"Encrypted:\n"&ant&"\n")
puts(1,"Decrypted:\n"&dec&"\n")</lang>
{{out}}
<pre>
Encrypted:
BacON's cIPHer Is a MEtHoD of stEgAnogRaphy crEatEd By FRaNcis baCOn.
thIs TASk Is TO imPLeMENt A proGrAm FOR eNcRYPTIoN anD deCRyPtioN Of
plAINTExt UsINg The SIMpLe AlPhaBet Of thE BAcOnIan CIphER Or oTheR
RePreSeNTation OF thIS AlphABeT. the bACoNIAn alPHa
Decrypted:
the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|Python}}==
7,796

edits