Bacon cipher: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(38 intermediate revisions by 18 users not shown)
Line 1:
{{draft task}} [[Category:Encryption]]
{{draft task}}
 
[[wp: Bacon's cipher| 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 some other kind of representation of this alphabet (make anything signify anything).
Line 15 ⟶ 17:
# It is impractical to use the original change in font for the steganography. For this task you must provide an example that uses a change in the case of successive alphabetical characters instead. Other examples for the language are encouraged to explore alternative steganographic means.
# Show an example plaintext message encoded and then decoded here on this page.
<br><br>
 
=={{header|11l}}==
{{trans|Nim}}
 
<syntaxhighlight lang="11l">V codes = [‘a’ = ‘AAAAA’, ‘b’ = ‘AAAAB’, ‘c’ = ‘AAABA’, ‘d’ = ‘AAABB’, ‘e’ = ‘AABAA’,
‘f’ = ‘AABAB’, ‘g’ = ‘AABBA’, ‘h’ = ‘AABBB’, ‘i’ = ‘ABAAA’, ‘j’ = ‘ABAAB’,
‘k’ = ‘ABABA’, ‘l’ = ‘ABABB’, ‘m’ = ‘ABBAA’, ‘n’ = ‘ABBAB’, ‘o’ = ‘ABBBA’,
‘p’ = ‘ABBBB’, ‘q’ = ‘BAAAA’, ‘r’ = ‘BAAAB’, ‘s’ = ‘BAABA’, ‘t’ = ‘BAABB’,
‘u’ = ‘BABAA’, ‘v’ = ‘BABAB’, ‘w’ = ‘BABBA’, ‘x’ = ‘BABBB’, ‘y’ = ‘BBAAA’,
‘z’ = ‘BBAAB’, ‘ ’ = ‘BBBAA’]
 
V rev_codes = Dict(codes.items(), (k, v) -> (v, k))
 
F encode(plaintext, message)
V et = ‘’
L(c) plaintext.lowercase()
et ‘’= I c C ‘a’..‘z’ {:codes[c]} E :codes[Char(‘ ’)]
 
V result = ‘’
V count = 0
L(c) message.lowercase()
I c C ‘a’..‘z’
result ‘’= I et[count] == ‘A’ {c} E c.uppercase()
count++
I count == et.len
L.break
E
result ‘’= c
R result
 
F decode(message)
V result = ‘’
V et = ‘’
L(c) message
I c C (‘A’..‘Z’, ‘a’..‘z’)
et ‘’= I c.is_lowercase() {‘A’} E ‘B’
L(i) (0 .< et.len - 4).step(5)
result ‘’= :rev_codes[et[i .< i + 5]]
R result
 
V plaintext = ‘the quick brown fox jumps over the lazy dog’
V message = ‘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 some ’""
‘other kind of representation of this alphabet (make anything signify anything). ’""
‘the baconian alphabet may optionally be extended to encode all lower ’""
‘case characters individually and/or adding a few punctuation characters ’""
‘such as the space.’
 
V ciphertext = encode(plaintext, message)
print(‘Cipher text →’)
print(ciphertext)
V decodedtext = decode(ciphertext)
print("\nHidden text →")
print(decodedtext)</syntaxhighlight>
 
{{out}}
<pre>
Cipher text →
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text →
the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|Ada}}==
{{trans|Kotlin}}
<syntaxhighlight lang="ada">-- Bacon cipher
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Containers.Ordered_Maps;
 
procedure Main is
subtype encode_str is String (1 .. 5);
subtype lower_case is Character range 'a' .. 'z';
subtype Upper_case is Character range 'A' .. 'Z';
package Alphabet is new Ada.Containers.Ordered_Maps
(Key_Type => Character, Element_Type => encode_str);
use Alphabet;
blank : constant Character := ' ';
 
Bacon : Map;
 
function encode (Plain_Text : String; Message : String) return String is
plain_lower : String := To_Lower (Plain_Text);
temp : Unbounded_String;
msg_lower : String := To_Lower (Message);
str : encode_str;
 
begin
for c of plain_lower loop
if c in lower_case then
str := Bacon.Element (c);
else
str := Bacon.Element (blank);
end if;
Append (Source => temp, New_Item => str);
end loop;
 
declare
encoded : String := To_String (temp);
Count : Positive := encoded'First;
result : Unbounded_String;
begin
for c of msg_lower loop
exit when Count > encoded'last;
if c in lower_case then
if encoded (Count) = 'A' then
Append (Source => result, New_Item => c);
else
Append (Source => result, New_Item => To_Upper (c));
end if;
Count := Count + 1;
else
Append (Source => result, New_Item => c);
end if;
end loop;
return To_String (result);
end;
end encode;
 
function Index (Item : Map; Pattern : encode_str) return Character is
result : Character := ' ';
value : encode_str;
begin
for key in lower_case loop
value := Item.Element (key);
if value = Pattern then
result := key;
exit;
end if;
end loop;
return result;
end Index;
 
function decode (Message : String) return String is
encoded : Unbounded_String;
begin
for c of Message loop
if c in lower_case then
Append (Source => encoded, New_Item => 'A');
elsif c in Upper_case then
Append (Source => encoded, New_Item => 'B');
end if;
end loop;
 
declare
encoded_string : String := To_String (encoded);
idx : Positive := encoded_string'First;
Result : Unbounded_String;
c : Character;
str : encode_str;
 
begin
loop
str := encoded_string (idx .. idx + 4);
c := Index (Item => Bacon, Pattern => str);
Append (Source => Result, New_Item => c);
idx := idx + 5;
exit when idx + 4 > encoded_string'Last;
end loop;
return To_String (Result);
end;
end decode;
 
P_Text : String := "the quick brown fox jumps over the lazy dog";
P_Msg : String :=
"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 some " &
"other kind of representation of this alphabet (make anything signify anything). " &
"the baconian alphabet may optionally be extended to encode all lower " &
"case characters individually and/or adding a few punctuation characters " &
"such as the space.";
 
begin
Bacon.Insert (Key => 'a', New_Item => "AAAAA");
Bacon.Insert (Key => 'b', New_Item => "AAAAB");
Bacon.Insert (Key => 'c', New_Item => "AAABA");
Bacon.Insert (Key => 'd', New_Item => "AAABB");
Bacon.Insert (Key => 'e', New_Item => "AABAA");
Bacon.Insert (Key => 'f', New_Item => "AABAB");
Bacon.Insert (Key => 'g', New_Item => "AABBA");
Bacon.Insert (Key => 'h', New_Item => "AABBB");
Bacon.Insert (Key => 'i', New_Item => "ABAAA");
Bacon.Insert (Key => 'j', New_Item => "ABAAB");
Bacon.Insert (Key => 'k', New_Item => "ABABA");
Bacon.Insert (Key => 'l', New_Item => "ABABB");
Bacon.Insert (Key => 'm', New_Item => "ABBAA");
Bacon.Insert (Key => 'n', New_Item => "ABBAB");
Bacon.Insert (Key => 'o', New_Item => "ABBBA");
Bacon.Insert (Key => 'p', New_Item => "ABBBB");
Bacon.Insert (Key => 'q', New_Item => "BAAAA");
Bacon.Insert (Key => 'r', New_Item => "BAAAB");
Bacon.Insert (Key => 's', New_Item => "BAABA");
Bacon.Insert (Key => 't', New_Item => "BAABB");
Bacon.Insert (Key => 'u', New_Item => "BABAA");
Bacon.Insert (Key => 'v', New_Item => "BABAB");
Bacon.Insert (Key => 'w', New_Item => "BABBA");
Bacon.Insert (Key => 'x', New_Item => "BABBB");
Bacon.Insert (Key => 'y', New_Item => "BBAAA");
Bacon.Insert (Key => 'z', New_Item => "BBAAB");
Bacon.Insert (Key => blank, New_Item => "BBBAA");
 
declare
ciphertext : String := encode (Plain_Text => P_Text, Message => P_Msg);
begin
Put_Line ("Cipher text:");
Put_Line (ciphertext);
New_Line;
Put_Line ("Hidden text:");
Put_Line (decode (ciphertext));
end;
end Main;</syntaxhighlight>
{{output}}
<pre>
Cipher text:
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text:
the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|Agena}}==
Tested with Agena 2.9.5 Win32
{{Trans|ALGOL 68}}
<langsyntaxhighlight lang="agena"># Bacon cipher
 
# Bacon's letter codes but with distinct values for i & j and u & v and an extra for any non-letter
Line 109 ⟶ 337:
print( "-----------------------------------------------------" );
print( if baconDecoded <> plainText then "UNSUCESSFUL" else "sucessful" fi, " decode" )
epocs</langsyntaxhighlight>
{{out}}
<pre>
Line 125 ⟶ 353:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># Bacon's letter codes but with distinct values for i & j and u & v and an extra for any non-letter #
[]STRING bacon codes = ( #a# "AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA"
, #j# "ABAAB", "ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB"
Line 212 ⟶ 440:
print( ( bacon decoded, newline ) );
print( ( "-----------------------------------------------------", newline ) );
print( ( IF bacon decoded /= plain text THEN "UNSUCESSFUL" ELSE "sucessful" FI, " decode", newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 227 ⟶ 455:
</pre>
 
=={{header|BaConArturo}}==
 
<syntaxhighlight lang="rebol">Codes: #[
a: "AAAAA" b: "AAAAB" c: "AAABA" d: "AAABB" e: "AABAA"
f: "AABAB" g: "AABBA" h: "AABBB" i: "ABAAA" j: "ABAAB"
k: "ABABA" l: "ABABB" m: "ABBAA" n: "ABBAB" o: "ABBBA"
p: "ABBBB" q: "BAAAA" r: "BAAAB" s: "BAABA" t: "BAABB"
u: "BABAA" v: "BABAB" w: "BABBA" x: "BABBB" y: "BBAAA"
z: "BBAAB"
]
space: "BBBAA"
 
RevCodes: #[]
loop Codes [k,v]-> RevCodes\[v]: k
 
encodeBacon: function [plaintext,message][
et: new ""
result: new ""
loop lower plaintext 'c [
'et ++ (lower? c)? -> Codes\[c] -> space
]
cnt: 0
loop lower message 'c [
if? lower? c [
'result ++ (et\[cnt] = `A`)? -> c -> upper c
cnt: cnt + 1
if cnt = size et -> break
]
else -> 'result ++ c
]
return result
]
 
decodeBacon: function [message][
et: new ""
result: new ""
loop message 'c [
if or? lower? c upper? c [
if? lower? c -> 'et ++ `A`
else -> 'et ++ `B`
 
if 5 = size et [
if? key? RevCodes et -> 'result ++ RevCodes\[et]
else -> 'result ++ " "
et: new ""
]
]
]
return result
]
 
PlainText: "the quick brown fox jumps over the lazy dog"
Message: join [
"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 some "
"other kind of representation of this alphabet (make anything signify anything). "
"the baconian alphabet may optionally be extended to encode all lower "
"case characters individually and/or adding a few punctuation characters "
"such as the space."
]
 
cipherText: encodeBacon PlainText Message
print "Cipher text:"
print cipherText
print ""
print "Message:"
print decodeBacon cipherText</syntaxhighlight>
 
{{out}}
 
<pre>Cipher text:
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Message:
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">Bacon_Cipher(message, plaintext:=""){
codes := {"a":"AAAAA", "b":"AAAAB", "c":"AAABA", "d":"AAABB", "e":"AABAA"
, "f":"AABAB", "g":"AABBA", "h":"AABBB", "i":"ABAAA", "j":"ABAAB"
, "k":"ABABA", "l":"ABABB", "m":"ABBAA", "n":"ABBAB", "o":"ABBBA"
, "p":"ABBBB", "q":"BAAAA", "r":"BAAAB", "s":"BAABA", "t":"BAABB"
, "u":"BABAA", "v":"BABAB", "w":"BABBA", "x":"BABBB", "y":"BBAAA"
, "z":"BBAAB", " ":"BBBAA"}
if (plaintext<>"") {
for i, letter in StrSplit(plaintext)
code .= codes[letter]
x := StrSplit(code)
for i, letter in StrSplit(message)
if (Asc(letter) >= 97 and Asc(letter) <= 122)
if !(l := x.RemoveAt(1))
break
else if (l = "A")
cipher .= letter
else
cipher .= Chr(Asc(letter) - 32)
else
cipher .= letter
return cipher
} else {
Keys := []
for l, c in codes
Keys[c] := l
for i, letter in StrSplit(message)
if (Asc(letter) >= 97 and Asc(letter) <= 122)
pattern .= "A"
else if (Asc(letter) >= 65 and Asc(letter) <= 90)
pattern .= "B"
while StrLen(pattern)
str .= Keys[SubStr(pattern, 1, 5)]
, pattern := SubStr(pattern, 6)
return str
}
}</syntaxhighlight>
Examples:<syntaxhighlight lang="autohotkey">Message:= "
(join
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 some
other kind of representation of this alphabet (make anything signify anything).
the baconian alphabet may optionally be extended to encode all lower
case characters individually and/or adding a few punctuation characters
such as the space.
)"
 
plaintext := "the quick brown fox jumps over the lazy dog"
 
MsgBox, 262144, ,% "plain text = " plaintext
. "`n`nencoded = `n" (cipher := Bacon_Cipher(message, plaintext))
. "`n`ndecoded = " recoveredText := Bacon_Cipher(cipher)</syntaxhighlight>
{{out}}
<pre>plain text = the quick brown fox jumps over the lazy dog
 
encoded =
BacON's cIPHer Is a METhoD of stEgAnogRaphy crEatEd By FRAncis baCOn.thIs TASk Is TO imPLeMENT a proGrAm FOR eNcRYPTIOn anD deCRyPtioN OfplAINTExt UsING the SIMpLe AlPhaBet Of thE BAConIan CIphER Or sOmeOTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
decoded = the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
A Bacon cipher in [[BaCon]]. Using unique identifiers 'aaaaa'-'bbaab' for a-z and, as other examples on this page, using 'bbbaa' (28) for the space character.
<langsyntaxhighlight lang="qbasic">msg$ = "the quick brown fox jumps over the lazy dog"
 
txt$ = "Bacon's cipher is a method of steganography created by Francis Bacon." \
Line 278 ⟶ 651:
NEXT
 
PRINT "Decoded:", NL$, result$</langsyntaxhighlight>
{{out}}
<pre>Encoded:
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
Decoded:
the quick brown fox jumps over the lazy dog</pre>
 
==={{header|Visual Basic .NET}}===
{{trans|C#}}
<syntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
 
ReadOnly CODES As New Dictionary(Of Char, String) From {
{"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"},
{"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"},
{"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"},
{"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"},
{"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"},
{"z", "BBAAB"}, {" ", "BBBAA"} ' use " " To denote any non-letter
}
 
Function Encode(plainText As String, message As String) As String
Dim pt = plainText.ToLower()
Dim sb As New StringBuilder()
For Each c In pt
If "a" <= c AndAlso c <= "z" Then
sb.Append(CODES(c))
Else
sb.Append(CODES(" "))
End If
Next
 
Dim et = sb.ToString()
Dim mg = message.ToLower() '"A"s to be in lower case, "B"s in upper case
 
sb.Length = 0
Dim count = 0
For Each c In mg
If "a" <= c AndAlso c <= "z" Then
If et(count) = "A" Then
sb.Append(c)
Else
sb.Append(Chr(Asc(c) - 32)) ' upper case equivalent
End If
count += 1
If count = et.Length Then
Exit For
End If
Else
sb.Append(c)
End If
Next
 
Return sb.ToString()
End Function
 
Function Decode(message As String) As String
Dim sb As New StringBuilder
 
For Each c In message
If "a" <= c AndAlso c <= "z" Then
sb.Append("A")
ElseIf "A" <= c AndAlso c <= "Z" Then
sb.Append("B")
End If
Next
 
Dim et = sb.ToString()
sb.Length = 0
For index = 0 To et.Length - 1 Step 5
Dim quintet = et.Substring(index, 5)
Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key
sb.Append(key)
Next
 
Return sb.ToString()
End Function
 
Sub Main()
Dim plainText = "the quick brown fox jumps over the lazy dog"
Dim message =
"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 some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
 
Dim cipherText = Encode(plainText, message)
Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText)
 
Dim decodedText = Decode(cipherText)
Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText)
End Sub
 
End Module</syntaxhighlight>
{{out}}
<pre>Cipher text ->
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text ->
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|C}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <stdlib.h>
Line 396 ⟶ 867:
free(hidden_text);
return 0;
}</langsyntaxhighlight>
 
{{output}}
Line 411 ⟶ 882:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 483 ⟶ 954:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 494 ⟶ 965:
Bacon cipher implementation
 
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 542 ⟶ 1,013:
std::vector<std::string> bAlphabet;
};
</syntaxhighlight>
</lang>
 
These next 2 classes use the 0's & 1's generated by the 'Bacon encryption' to create different the outputs.
One could go wild here...
<langsyntaxhighlight lang="cpp">
class cipherI {
public:
Line 618 ⟶ 1,089:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 632 ⟶ 1,103:
LETSHAUESOMEFUNWITHBACONCIPHER
</pre>
 
=={{header|Common Lisp}}==
 
====Association lists====
 
1. Note
 
Codes are stored in association lists.
 
<pre>#\x -> assoc -> code -> rassoc -> #\x</pre>
 
For instance.
 
<pre>(cdr (assoc #\a +codes+)) = (a a a a a) (car (rassoc '(a a a a a) +codes+) = #\a </pre>
 
2. Program
 
<syntaxhighlight lang="lisp">;; 22.06.16
 
(defconstant +codes+
'((#\a . (a a a a a)) (#\b . (a a a a b)) (#\c . (a a a b a))
(#\d . (a a a b b)) (#\e . (a a b a a)) (#\f . (a a b a b))
(#\g . (a a b b a)) (#\h . (a a b b b)) (#\i . (a b a a a))
(#\j . (a b a a b)) (#\k . (a b a b a)) (#\l . (a b a b b))
(#\m . (a b b a a)) (#\n . (a b b a b)) (#\o . (a b b b a))
(#\p . (a b b b b)) (#\q . (b a a a a)) (#\r . (b a a a b))
(#\s . (b a a b a)) (#\t . (b a a b b)) (#\u . (b a b a a))
(#\v . (b a b a b)) (#\w . (b a b b a)) (#\x . (b a b b b))
(#\y . (b b a a a)) (#\z . (b b a a b)) (#\space . (b b b a a))))
 
(defun encode (text message)
(let (cipher key code)
(loop for c across message do
(setf code (cdr (assoc (char-downcase c) +codes+)))
(setf key (append key code)))
(loop for c across text always key do
(when (alpha-char-p c)
(if (eq (car key) 'B)
(setf c (char-upcase c))
(setf c (char-downcase c)))
(setf key (cdr key)))
(setf cipher (append cipher (list c))))
(coerce cipher 'string)))
 
(defun decode (message)
(let (key code letter)
(loop for c across message when (alpha-char-p c) do
(if (lower-case-p c)
(setf code (append code '(A)))
(setf code (append code '(B))))
(when (= (length code) 5)
(setf letter (car (rassoc code +codes+ :test #'equal)))
(setf key (append key (list letter)))
(setf code nil)))
(coerce key 'string)))</syntaxhighlight>
 
3. Example
 
<syntaxhighlight lang="lisp">(defconstant +monologue+ (concatenate 'string
"I've known adventures, seen places you people will never see, I've been Offw"
"orld and back... frontiers ! I've stood on the back deck of a blinker bound "
"for the Plutition Camps with sweat in my eyes watching stars fight on the sh"
"oulder of Orion... I’ve felt wind in my hair, riding test boats off the blac"
"k galaxies and seen an attack fleet burn like a match and disappear. I've se"
"en it, felt it..."))
 
(defconstant +key+ "« tears in rain »")</syntaxhighlight>
 
4. Execution
 
{{out}}
<pre>(encode +monologue+ +key+)
"I'VE knOwn ADveNtures, seEn plACes YoU PEoplE will NEvER SEe, i'Ve beEn offwoRl
d anD BaCK... FRon"
(decode (encode +monologue+ +key+))
" tears in rain "</pre>
 
That's All Folks !
 
''cyril nocton (cyril.nocton@gmail.com)''
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.array;
import std.stdio;
import std.uni;
Line 723 ⟶ 1,274:
writeln("Hidden text ->");
writeln(decodedText);
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 733 ⟶ 1,284:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Bacon%27s_cipher}}
In [https://wiki.formulae.org/Bacon_cipher this] page you can see the solution of this task.
 
'''Solution'''
 
'''Program for encoding.''' It uses the extended version of the alphabeth, which can be calculated programatically, with no table.
 
[[File:Fōrmulæ - Bacon's cipher 01.png]]
 
'''Test case for encoding'''
 
[[File:Fōrmulæ - Bacon's cipher 02.png]]
 
[[File:Fōrmulæ - Bacon's cipher 03.png]]
 
'''Program for decoding'''
 
[[File:Fōrmulæ - Bacon's cipher 04.png]]
 
'''Test case for decoding'''
 
[[File:Fōrmulæ - Bacon's cipher 05.png]]
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Bacon's cipher 06.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import(
Line 823 ⟶ 1,392:
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}</langsyntaxhighlight>
 
{{out}}
Line 838 ⟶ 1,407:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class BaconCipher {
private static final Map<Character, String> codes
 
Line 925 ⟶ 1,494:
System.out.printf("\nHidden text ->\n\n%s\n", decodedText)
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 937 ⟶ 1,506:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">-- Necessary imports
import Data.List (elemIndex, unfoldr)
import Data.Bool (bool)
Line 1,009 ⟶ 1,578:
, encode text "something wrong @ in the message"
, encode "abc" message
]</langsyntaxhighlight>
{{Out}}
<pre>BAcoN's CIPher is A metHod Of StegaNogrApHy creAted By franCiS
Line 1,028 ⟶ 1,597:
Implementation:
 
<langsyntaxhighlight Jlang="j">alfa=: 'ABCDEFGHIKLMNOPQRSTUWXYZ'
beta=: 26{.(}.~i.&'A')a.
norm=: ([ -. -.)&alfa@(rplc&('JIVU'))@toupper
Line 1,035 ⟶ 1,604:
 
encrypt=: gena@enca@norm
decrypt=: alfa {~ _5 #.\ 90 < a.&i.</langsyntaxhighlight>
 
We use random letters as the basis for our steganography and we use case to represent "font".
Line 1,041 ⟶ 1,610:
Example use:
 
<langsyntaxhighlight Jlang="j"> encrypt 'this is a test'
nWVkJAPkamEuUJIeTGKnUsTVRfAWWuNBIIHdEIcOAPuTBeXKQduQAdU
encrypt 'this is a test'
sFLkBQKqqaQsGGXzAXQsKlZFBcILRlUIRAQaEQoNUBcHIhFTWbeRAlM
decrypt encrypt 'this is a test'
THISISATEST</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
{{works with|Java|9}}
<langsyntaxhighlight Javalang="java">import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
Line 1,126 ⟶ 1,695:
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 1,136 ⟶ 1,705:
the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|jq}}==
{{trans|Wren}}
{{works with|jq}}
'''Works with gojq, the Go implementation of jq''' (*)
 
'''Preliminaries'''
<syntaxhighlight lang="jq">def is_upper: . >= "A" and . <= "Z";
 
def is_lower: . >= "a" and . <= "z";
 
# Output: a stream
def chars: explode[] | [.] | implode;
 
# (*) Change to `keys` for gojq
def key($s): first( keys_unsorted[] as $k | if .[$k] == $s then $k else empty end) // "?";
</syntaxhighlight>
'''Bacon Cipher'''
<syntaxhighlight lang="jq">def Bacon:
{
"a" : "AAAAA", "b" : "AAAAB", "c" : "AAABA", "d" : "AAABB", "e" : "AABAA",
"f" : "AABAB", "g" : "AABBA", "h" : "AABBB", "i" : "ABAAA", "j" : "ABAAB",
"k" : "ABABA", "l" : "ABABB", "m" : "ABBAA", "n" : "ABBAB", "o" : "ABBBA",
"p" : "ABBBB", "q" : "BAAAA", "r" : "BAAAB", "s" : "BAABA", "t" : "BAABB",
"u" : "BABAA", "v" : "BABAB", "w" : "BABBA", "x" : "BABBB", "y" : "BBAAA",
"z" : "BBAAB", " " : "BBBAA" # use " " to denote any non-letter
};
 
def encode($plaintext; $message):
(reduce ($plaintext|ascii_downcase|chars) as $c ("";
if $c|ascii_downcase == . then . + Bacon[$c] else . + Bacon[" "] end)) as $et
# "A"s to be in lower case, "B"s in upper case
| label $out
| foreach ($message|ascii_downcase|chars) as $c ( {sb: "", count: 0};
if ($c | is_lower)
then .sb = if $et[.count: .count+1] == "A" then .sb + $c else .sb + ($c|ascii_upcase) end
| .count += 1
| if .count == ($et|length) then .emit = .sb, break $out else . end
else .sb += $c
end;
select(.emit).emit ) ;
 
def decode($message):
Bacon as $Bacon
| (reduce ($message|chars) as $c ("";
if ($c|is_lower) then . + "A"
elif ($c|is_upper) then . + "B"
else .
end)) as $et
| reduce range(0; $et|length; 5) as $i ("";
$et[$i : $i+5] as $quintet
| . + ($Bacon | key($quintet)) ) ;
 
 
{ plainText: "the quick brown fox jumps over the lazy dog",
message: (
"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 some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space.") }
| .cipherText = encode(.plainText; .message)
| .decodedText = decode(.cipherText)
| "Cipher text ->\n\n\(.cipherText)",
"\nHidden text ->\n\n\(.decodedText)"</syntaxhighlight>
{{out}}
<pre>
Cipher text ->
 
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text ->
 
the quick brown fox jumps over the lazy dog
</pre>
 
 
=={{header|Julia}}==
Line 1,142 ⟶ 1,789:
 
'''Module''':
<langsyntaxhighlight lang="julia">module BaconCipher
 
using Formatting, IterTools.chain
Line 1,207 ⟶ 1,854:
end
 
end # module BaconCipher</langsyntaxhighlight>
 
'''Main''':
<langsyntaxhighlight lang="julia">let msg = "Rosetta code Bacon cipher example secret phrase to encode in the capitalisation of peter pan"
enc = BaconCipher.encrypt(msg)
dec = BaconCipher.decrypt(enc)
Line 1,216 ⟶ 1,863:
println(" -> Encrypted:\n", enc)
println(" -> Decrypted:\n", dec)
end</langsyntaxhighlight>
 
{{out}}
Line 1,238 ⟶ 1,885:
=={{header|Kotlin}}==
The 'full' Bacon alphabet, which has separate letters for i, j, u and v, has been used in the following:
<langsyntaxhighlight lang="scala">object Bacon {
private val codes = mapOf(
'a' to "AAAAA", 'b' to "AAAAB", 'c' to "AAABA", 'd' to "AAABB", 'e' to "AABAA",
Line 1,299 ⟶ 1,946:
val decodedText = Bacon.decode(cipherText)
println("\nHidden text ->\n\n$decodedText")
}</langsyntaxhighlight>
 
{{out}}
Line 1,314 ⟶ 1,961:
=={{header|Lua}}==
Based on C++ version
<syntaxhighlight lang="lua">
<lang Lua>
function Bacon( txt, secret, e )
local alpha = {}
Line 1,424 ⟶ 2,071:
print( a )
print( Bacon( "", a, 0 ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,433 ⟶ 2,080:
 
=={{header|MiniScript}}==
<langsyntaxhighlight MiniScriptlang="miniscript">c = {}
c["a"] = "AAAAA"; c["b"] = "AAAAB"; c["c"] = "AAABA"; c["d"] = "AAABB"; c["e"] = "AABAA"; c["f"] = "AABAB";
c["g"] = "AABBA"; c["h"] = "AABBB"; c["i"] = "ABAAA"; c["j"] = "ABAAB"; c["k"] = "ABABA"; c["l"] = "ABABB";
Line 1,496 ⟶ 2,143:
codedMsg = encode("the quick brown fox jumps over the lazy dog")
print codedMsg
print decode(codedMsg)</langsyntaxhighlight>
 
{{out}}
<pre>cOMpuTErs aRE eVErywHErE. THErE aRE ThE OBVIOuS OnEs, Like YOUR SMarT PHoNe or GaMe sYSteM. therE ARE lEsS obvIoUs ones, lIKE iN YouR mICRowAVE or youR BeDsidE CLock. AnD tHeN ThERe ARE the rEAlLY inVIsibLE oNEs, liKE ThE 50 or SO SMAll COmpuTERs in YOUR Car.All tHESe cO
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import strutils, sugar, tables
 
const Codes = {'a': "AAAAA", 'b': "AAAAB", 'c': "AAABA", 'd': "AAABB", 'e': "AABAA",
'f': "AABAB", 'g': "AABBA", 'h': "AABBB", 'i': "ABAAA", 'j': "ABAAB",
'k': "ABABA", 'l': "ABABB", 'm': "ABBAA", 'n': "ABBAB", 'o': "ABBBA",
'p': "ABBBB", 'q': "BAAAA", 'r': "BAAAB", 's': "BAABA", 't': "BAABB",
'u': "BABAA", 'v': "BABAB", 'w': "BABBA", 'x': "BABBB", 'y': "BBAAA",
'z': "BBAAB", ' ': "BBBAA"}.toTable
 
let RevCodes = collect(newTable, for k, v in Codes.pairs: {v: k})
 
proc encode(plaintext, message: string): string =
var et: string
for c in plaintext.toLowerAscii:
et.add if c in 'a'..'z': Codes[c] else: Codes[' ']
var count = 0
for c in message.toLowerAscii:
if c in 'a'..'z':
result.add if et[count] == 'A': c else: c.toUpperAscii
inc count
if count == et.len: break
else:
result.add c
 
 
proc decode(message: string): string =
var et: string
for c in message:
if c.isAlphaAscii:
et.add if c.isLowerAscii: 'A' else: 'B'
for i in countup(0, et.high - 4, 5):
result.add RevCodes[et[i..(i+4)]]
 
 
when isMainModule:
const
PlainText = "the quick brown fox jumps over the lazy dog"
Message = "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 some " &
"other kind of representation of this alphabet (make anything signify anything). " &
"the baconian alphabet may optionally be extended to encode all lower " &
"case characters individually and/or adding a few punctuation characters " &
"such as the space."
let cipherText = PlainText.encode(Message)
echo "Cipher text →\n", cipherText
let decodedText = cipherText.decode()
echo "\nHidden text →\n", decodedText</syntaxhighlight>
 
{{out}}
<pre>Cipher text →
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text →
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use utf8;
Line 1,568 ⟶ 2,273:
 
print "$steganography\n"
print "$decoded\n"</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">Steganograpic message hidden in text:
Line 1,607 ⟶ 2,312:
half of/an obviously corrupt image file.
 
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>constant bits = 5,
<span style="color: #008080;">constant</span> <span style="color: #000000;">bits</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5</span><span style="color: #0000FF;">,</span>
mask = power(2,bits-1)
<span style="color: #000000;">mask</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
 
function bacon(string msg, plaintext)
<span style="color: #008080;">function</span> <span style="color: #000000;">bacon</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span>
plaintext = lower(plaintext)
<span style="color: #000000;">plaintext</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span>
integer ptdx = 0
<span style="color: #004080;">integer</span> <span style="color: #000000;">ptdx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
for i=1 to length(msg) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer inch = lower(msg[i])-'a'
<span style="color: #004080;">integer</span> <span style="color: #000000;">inch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])-</span><span style="color: #008000;">'a'</span>
if inch<0 or inch>25 then inch = 26 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">inch</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">inch</span><span style="color: #0000FF;">></span><span style="color: #000000;">25</span> <span style="color: #008080;">then</span> <span style="color: #000000;">inch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">26</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer m = mask
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mask</span>
while true do -- encode one character
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- encode one character</span>
while true do -- find an a-z for this bit
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span> <span style="color: #000080;font-style:italic;">-- find an a-z for this bit</span>
ptdx += 1
<span style="color: #000000;">ptdx</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
if ptdx>length(plaintext) then
<span style="color: #008080;">if</span> <span style="color: #000000;">ptdx</span><span style="color: #0000FF;">></span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
crash("plaintext too short")
<span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"plaintext too short"</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer ch = plaintext[ptdx]
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">plaintext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ptdx</span><span style="color: #0000FF;">]</span>
if ch>='a' and ch<='z' then
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'z'</span> <span style="color: #008080;">then</span>
if and_bits(inch,m) then
<span style="color: #008080;">if</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">inch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
plaintext[ptdx] = upper(ch)
<span style="color: #000000;">plaintext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">ptdx</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
exit
end if <span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
if m=1 then exit end if
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
m /= 2
<span style="color: #000000;">m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return plaintext[1..ptdx]
<span style="color: #008080;">return</span> <span style="color: #000000;">plaintext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ptdx</span><span style="color: #0000FF;">]</span>
-- return plaintext -- note: yields ...dogaaaaaaaaaa.....
<span style="color: #000080;font-style:italic;">-- return plaintext -- note: yields ...dogaaaaaaaaaa.....</span>
end function -- [or the "oops?" in nocab()]
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> <span style="color: #000080;font-style:italic;">-- [or the "oops?" in nocab()]</span>
 
function nocab(string plaintext)
<span style="color: #008080;">function</span> <span style="color: #000000;">nocab</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span>
string res = ""
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
integer m = mask, ch = 'a'
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mask</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'a'</span>
for i=1 to length(plaintext) do
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
integer inch = lower(plaintext[i])
<span style="color: #004080;">integer</span> <span style="color: #000000;">inch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
if inch>='a' and inch<='z' then
<span style="color: #008080;">if</span> <span style="color: #000000;">inch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">and</span> <span style="color: #000000;">inch</span><span style="color: #0000FF;"><=</span><span style="color: #008000;">'z'</span> <span style="color: #008080;">then</span>
if inch!=plaintext[i] then
<span style="color: #008080;">if</span> <span style="color: #000000;">inch</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
ch += m
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">m</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if m=1 then
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
res &= iff(ch>'z'?' ':ch)
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #008000;">'z'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">:</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
m = mask
<span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">mask</span>
ch = 'a'
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'a'</span>
else
<span style="color: m #008080;">else</= 2span>
<span style="color: #000000;">m</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if m!=mask or ch!='a' then crash("oops?") end if
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">mask</span> <span style="color: #008080;">or</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">!=</span><span style="color: #008000;">'a'</span> <span style="color: #008080;">then</span> <span style="color: #7060A8;">crash</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"oops?"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
return res
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
end function
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
 
constant plaintext = """
<span style="color: #008080;">constant</span> <span style="color: #000000;">plaintext</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Bacon's cipher is a method of steganography created by Francis Bacon.
Bacon's cipher is a method of steganography created by Francis Bacon.
This task is to implement a program for encryption and decryption of
This task is to implement a program for encryption and decryption of
plaintext using the simple alphabet of the baconian cipher or other
plaintext using the simple alphabet of the baconian cipher or other
representation of this alphabet. The baconian alphabet may optionally
representation of this alphabet. The baconian alphabet may optionally
be extended to encode all lower case characters individually and/or
be extended to encode all lower case characters individually and/or
add a few punctuation characters such as the space."""
add a few punctuation characters such as the space."""</span>
 
constant msg = "The quick brown fox jumps over the lazy dog"
<span style="color: #008080;">constant</span> <span style="color: #000000;">msg</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"The quick brown fox jumps over the lazy dog"</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">ant</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bacon</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span><span style="color: #000000;">plaintext</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">dec</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nocab</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ant</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Encrypted:\n"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">ant</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Decrypted:\n"</span><span style="color: #0000FF;">&</span><span style="color: #000000;">dec</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
 
string ant = bacon(msg,plaintext),
dec = nocab(ant)
puts(1,"Encrypted:\n"&ant&"\n")
puts(1,"Decrypted:\n"&dec&"\n")</lang>
{{out}}
<pre>
Line 1,689 ⟶ 2,397:
This deviates from the Bacon method as it encodes to different capitalisation of text rather than differences in font.
 
<langsyntaxhighlight lang="python">import string
 
sometext = """All children, except one, grow up. They soon know that they will grow
Line 1,755 ⟶ 2,463:
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'</langsyntaxhighlight>
 
{{out}}
Line 1,775 ⟶ 2,483:
DECRYPTED =
rosetta code bacon cipher example secret phrase to encode in the capitalisation of peter pan</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ dup upper swap lower != ] is ischar ( c --> b )
 
[ char a char z 1+ clamp
char a -
[ table
$ "AAAAA" $ "AAAAB" $ "AAABA" ( abc )
$ "AAABB" $ "AABAA" $ "AABAB" ( def )
$ "AABBA" $ "AABBB" $ "ABAAA" ( ghi )
$ "ABAAB" $ "ABABA" $ "ABABB" ( jkl )
$ "ABBAA" $ "ABBAB" $ "ABBBA" ( mno )
$ "ABBBB" $ "BAAAA" $ "BAAAB" ( pqr )
$ "BAABA" $ "BAABB" $ "BABAA" ( stu )
$ "BABAB" $ "BABBA" $ "BABBB" ( vwx )
$ "BBAAA" $ "BBAAB" ( y z ) ] do ] is baconian ( c --> $ )
[ $ "abcdefghijklmnopqrstuvwxyz"
0 rot witheach
[ char A = swap 1 << + ]
0 25 clamp peek ] is debacon ( $ --> c )
 
[ [] swap
witheach
[ dup ischar iff
[ lower baconian join ]
else drop ] ] is ->bacon$ ( $ --> $ )
 
[ [] [] rot
dup size 5 / times
[ 5 split
dip [ nested join ] ]
drop
witheach [ debacon join ] ] is debacon$ ( $ --> $ )
 
[ [] unrot ->bacon$ swap
witheach
[ over size if
[ dup ischar if
[ swap behead
dip swap
char A = iff
lower else upper ] ]
swap dip join ] drop ] is baconise ( $ $ --> $ )
 
[ [] swap
witheach
[ dup ischar iff
[ char A char Z 1+ within iff
[ char A ] else [ char B ]
join ]
else drop ]
debacon$ ] is debaconise ( $ --> $ )
 
$ "If it looks like a duck, and quacks like a duck, "
$ "we have at least to consider the possibility that "
$ "we have a small aquatic bird of the family anatidae "
$ " on our hands. "
$ "(This is a quote from the noted author Douglas Adams)"
4 times join
$ "Dirk Gently's Holistic Detective Agency"
baconise
dup nest$ 60 wrap$ cr cr
debaconise echo$
</syntaxhighlight>
 
{{out}}
 
<pre>if iT LoOks lIke a DuCk, And qUAcks Like A DuCK, we HAvE aT
LEAst tO coNsidER ThE POssIbILiTy thAt wE hAve A SmAll
aquaTic biRD of The FamILy aNatidaE oN ouR HaNds. (tHiS iS a
qUote from thE NoteD autHOr DougLaS Adams)
 
dirkgentlysholisticdetectiveagency</pre>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
(require xml)
 
Line 1,824 ⟶ 2,607:
)
(displayln (bacon-encode->html plain-text false-text values (λ (s) `(i ,s)))))</langsyntaxhighlight>
 
{{out}}
Line 1,842 ⟶ 2,625:
=={{header|Raku}}==
(formerly Perl 6)
=== alternative steganography algorithm ===
Not truly a Bacon Cipher as it doesn't encode using font variations. But fits with the spirit if not the exact definition.
{{works with|Rakudo|2015-11-20}}
<syntaxhighlight lang="raku" perl6line>my $secret = q:to/END/;
This task is to implement a program for encryption and decryption
of plaintext using the simple alphabet of the Baconian cipher or
Line 1,897 ⟶ 2,681:
 
say "Hidden message revealed:";
say reveal $steganography;</langsyntaxhighlight>
 
{{out}}
Line 1,923 ⟶ 2,707:
signify anything). This example will work with anything in the
ASCII range... even code! $r%_-^&*(){}+~ #=`/\';*1234567890"'</pre>
 
=== Bacon cipher solution ===
<syntaxhighlight lang="raku" line>my @abc = 'a' .. 'z';
my @symb = ' ', |@abc; # modified Baconian charset - space and full alphabet
# TODO original one with I=J U=V, nice for Latin
 
my %bacon = @symb Z=> (^@symb).map(*.base(2).fmt("%05s"));
my %nocab = %bacon.antipairs;
 
sub bacon ($s, $msg) {
my @raw = $s.lc.comb;
my @txt := @raw[ (^@raw).grep({@raw[$_] (elem) @abc}) ];
for $msg.lc.comb Z @txt.batch(5) -> ($c-msg, @a) {
for @a.kv -> $i, $c-str {
(my $x := @a[$i]) = $x.uc if %bacon{$c-msg}.comb[$i].Int.Bool;
} }
@raw.join;
}
 
sub unbacon ($s) {
my $chunks = ($s ~~ m:g/\w+/)>>.Str.join.comb(/.**5/);
$chunks.map(*.comb.map({.uc eq $_})».Int».Str.join).map({%nocab{$_}}).join;
}
 
my $msg = "Omnes homines dignitate et iure liberi et pares nascuntur";
 
my $str = <Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa
qui officia deserunt mollit anim id est laborum.>;
 
my $baconed = bacon $str, $msg;
$baconed = $baconed.?naive-word-wrapper || $baconed;
# FIXME ^^^ makes dbl space after .
say "text:\n$baconed\n";
my $unbaconed = unbacon($baconed).trim.uc;
say "hidden message:\n$unbaconed";</syntaxhighlight>
 
{{out}}
<pre>text:
lOREM iPSuM dOLOr siT aMEt, cONsectetUr adiPISCiNG eLiT, seD dO EIusmOd
TEmpOR incididUnt uT laBorE ET dOLOre MagNA aLiqua. ut ENiM ad miNiM
veniam, qUiS NoStrud exerCitATiOn ULlaMco lAbOris nisI Ut alIquIp ex Ea
coMmODo cOnsEquAt. duis auTe IRuRe dolor iN reprehenDEriT in vOlUPtaTE
velit eSSE cilluM DolORe eu FUGiAt NuLLA pArIatUr. ExCEptEur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.
 
hidden message:
OMNES HOMINES DIGNITATE ET IURE LIBERI ET PARES NASCUNTUR</pre>
 
=={{header|REXX}}==
Line 1,934 ⟶ 2,771:
 
All alphabetic letters are handled as if they were in uppercase &nbsp; (i.e., lowercase letters are uppercased).
<langsyntaxhighlight lang="rexx">/*REXX program implements and demonstrates a (full) "Bacon" cipher (cypher).*/
parse arg plain /*obtain optional arguments from the CL*/
if plain='' then plain = "The quick brown fox jumped over the lazy dog."
Line 1,958 ⟶ 2,795:
do k=0 for 256; _=d2c(k); if @._=='' then iterate; q=@._; !.q=_; end
do j=1 to Lx by 5; y=substr(x,j,5); $=$ || !.y; end
return $</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 1,970 ⟶ 2,807:
:::* &nbsp; the &nbsp; ''bottom tee'' &nbsp; <big><big>┴</big></big> &nbsp; &nbsp; (sometimes known as the &nbsp; ''bottom junction'')
:::* &nbsp; the &nbsp; &nbsp; ''top tee'' &nbsp; &nbsp; &nbsp; <big><big>┬</big></big> &nbsp; &nbsp; (sometimes known as the &nbsp; ''top junction'')
<langsyntaxhighlight lang="rexx">/*REXX program implements and demonstrates a (full) "Bacon" cipher (cypher).*/
parse arg plain /*obtain optional arguments from the CL*/
if plain='' then plain = "The quick brown fox jumped over the lazy dog."
Line 1,994 ⟶ 2,831:
do k=0 for 256; _=d2c(k); if @._=='' then iterate; q=@._; !.q=_; end
do j=1 to Lx by 5; y=substr(x,j,5); $=$ || !.y; end
return $</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,003 ⟶ 2,840:
 
===uses upper/lower case===
<langsyntaxhighlight lang="rexx">/*REXX program implements and demonstrates a (full) "Bacon" cipher (cypher).*/
parse arg plain /*obtain optional arguments from the CL*/
if plain='' then plain = "The quick brown fox jumped over the lazy dog."
Line 2,027 ⟶ 2,864:
do k=0 for 256; _=d2c(k); if @._=='' then iterate; q=@._; !.q=_; end
do j=1 to Lx by 5; y=substr(x,j,5); $=$ || !.y; end
return $</langsyntaxhighlight>
'''output''' &nbsp; when using the default input:
<pre>
Line 2,037 ⟶ 2,874:
=={{header|Ruby}}==
{{trans|C#}}
<langsyntaxhighlight lang="ruby">CODES = {
'a' => "AAAAA", 'b' => "AAAAB", 'c' => "AAABA", 'd' => "AAABB", 'e' => "AABAA",
'f' => "AABAB", 'g' => "AABBA", 'h' => "AABBB", 'i' => "ABAAA", 'j' => "ABAAB",
Line 2,124 ⟶ 2,961:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 2,134 ⟶ 2,971:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import scala.util.control.Breaks._
 
object BaconCipher {
Line 2,222 ⟶ 3,059:
println(s"Hidden text ->\n\n$decodedText")
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 2,231 ⟶ 3,068:
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|VisualV Basic .NET(Vlang)}}==
{{trans|C#go}}
<syntaxhighlight lang="v (vlang)">const codes = {
<lang vbnet>Imports System.Text
`a` : "AAAAA", `b` : "AAAAB", `c` : "AAABA", `d` : "AAABB", `e` : "AABAA",
`f` : "AABAB", `g` : "AABBA", `h` : "AABBB", `i` : "ABAAA", `j` : "ABAAB",
`k` : "ABABA", `l` : "ABABB", `m` : "ABBAA", `n` : "ABBAB", `o` : "ABBBA",
`p` : "ABBBB", `q` : "BAAAA", `r` : "BAAAB", `s` : "BAABA", `t` : "BAABB",
`u` : "BABAA", `v` : "BABAB", `w` : "BABBA", `x` : "BABBB", `y` : "BBAAA",
`z` : "BBAAB", ` ` : "BBBAA"
}
 
fn bacon_encode(plain_text string, message string) string {
Module Module1
pt := plain_text.to_lower()
mut sb := []u8{}
for c in pt.runes() {
if c >= `a` && c <= `z` {
sb << codes[c].bytes()
} else {
sb << codes[` `].bytes()
}
}
et := sb.bytestr()
mg := message.to_lower() // 'A's to be in lower case, 'B's in upper case
sb = [] // clear the byte slice
mut count := 0
for c in mg {
if c >= u8(`a`) && c <= u8(`z`) {
if et[count] == `A` {
sb << c
} else {
sb << c - 32 // upper case equivalent
}
count++
if count == et.len { break }
} else {
sb << c
}
}
return sb.bytestr()
}
fn bacon_decode(message string) string {
mut sb := []u8{}
for c in message {
if c >= u8(`a`) && c <= u8(`z`) {
sb << `A`
} else if c >= u8(`A`) && c <= u8(`Z`) {
sb << `B`
}
}
et := sb.bytestr()
sb = [] // clear the byte slice
for i := 0; i < et.len; i += 5 {
quintet := et[i .. i + 5]
for k, v in codes {
if v == quintet {
sb << u8(k)
break
}
}
}
return sb.bytestr()
}
fn main() {
plain_text := "the quick brown fox jumps over the lazy dog"
message := "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 some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
cipher_text := bacon_encode(plain_text, message)
println("Cipher text ->\n\n$cipher_text")
decoded_text := bacon_decode(cipher_text)
println("\nHidden text ->\n\n$decoded_text")
}</syntaxhighlight>
{{out}}
<pre>
Cipher text ->
 
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text ->
ReadOnly CODES As New Dictionary(Of Char, String) From {
 
{"a", "AAAAA"}, {"b", "AAAAB"}, {"c", "AAABA"}, {"d", "AAABB"}, {"e", "AABAA"},
the quick brown fox jumps over the lazy dog</pre>
{"f", "AABAB"}, {"g", "AABBA"}, {"h", "AABBB"}, {"i", "ABAAA"}, {"j", "ABAAB"},
 
{"k", "ABABA"}, {"l", "ABABB"}, {"m", "ABBAA"}, {"n", "ABBAB"}, {"o", "ABBBA"},
=={{header|Wren}}==
{"p", "ABBBB"}, {"q", "BAAAA"}, {"r", "BAAAB"}, {"s", "BAABA"}, {"t", "BAABB"},
{{trans|Kotlin}}
{"u", "BABAA"}, {"v", "BABAB"}, {"w", "BABBA"}, {"x", "BABBB"}, {"y", "BBAAA"},
{{libheader|Wren-str}}
{"z", "BBAAB"}, {" ", "BBBAA"} ' use " " To denote any non-letter
{{libheader|Wren-iterate}}
<syntaxhighlight lang="wren">import "./str" for Str, Char
import "./iterate" for Stepped
 
class Bacon {
static init() {
__codes = {
"a" : "AAAAA", "b" : "AAAAB", "c" : "AAABA", "d" : "AAABB", "e" : "AABAA",
"f" : "AABAB", "g" : "AABBA", "h" : "AABBB", "i" : "ABAAA", "j" : "ABAAB",
"k" : "ABABA", "l" : "ABABB", "m" : "ABBAA", "n" : "ABBAB", "o" : "ABBBA",
"p" : "ABBBB", "q" : "BAAAA", "r" : "BAAAB", "s" : "BAABA", "t" : "BAABB",
"u" : "BABAA", "v" : "BABAB", "w" : "BABBA", "x" : "BABBB", "y" : "BBAAA",
"z" : "BBAAB", " " : "BBBAA" // use " " to denote any non-letter
}
}
 
Functionstatic Encodeencode(plainText As String, message As String) As String{
Dimvar pt = plainTextStr.ToLowerlower(plainText)
Dimvar sb As= New StringBuilder()""
for (c in pt) sb = Char.isLower(c) ? sb + __codes[c] : sb + __codes[" "]
For Each c In pt
var et If "a" <= c AndAlso c <= "z" Thensb
sb = sb.Append(CODES(c))""
var mg = Str.lower(message) // 'A's to be in lower case, 'B's in upper case
Else
var count = sb.Append(CODES(" "))0
for (c in mg) End If{
Next if (Char.isLower(c)) {
sb = (et[count] == "A") ? sb + c : sb + Char.upper(c)
count = count + 1
if (count == et.count) break
} else {
sb = sb + c
}
}
return sb
}
 
static decode(message) {
Dim et = sb.ToString()
var sb = ""
Dim mg = message.ToLower() '"A"s to be in lower case, "B"s in upper case
for (c in message) {
if (Char.isLower(c)) {
sb = sb + "A"
} else if (Char.isUpper(c)) {
sb = sb + "B"
}
}
var et = sb
sb = ""
for (i in Stepped.new(0...et.count, 5)) {
var quintet = Str.sub(et, i...i+5)
var key = __codes.keys.where { |k| __codes[k] == quintet }.toList[0]
sb = sb + key
}
return sb
}
}
 
Bacon.init()
sb.Length = 0
var plainText = "the quick brown fox jumps over the lazy dog"
Dim count = 0
var message =
For Each c In mg
"bacon's cipher is a method of steganography created by francis bacon." +
If "a" <= c AndAlso c <= "z" Then
"this task is to implement a program for encryption and decryption of " +
If et(count) = "A" Then
"plaintext using the simple alphabet of the baconian cipher or some " +
sb.Append(c)
"other kind of representation of this alphabet (make anything signify anything). " +
Else
"the baconian alphabet may optionally be extended to encode all lower " +
sb.Append(Chr(Asc(c) - 32)) ' upper case equivalent
"case characters individually and/or adding a few punctuation characters " +
End If
"such as the space."
count += 1
var cipherText = Bacon.encode(plainText, message)
If count = et.Length Then
System.print("Cipher text ->\n\n%(cipherText)")
Exit For
var decodedText = Bacon.decode(cipherText)
End If
System.print("\nHidden text ->\n\n%(decodedText)")</syntaxhighlight>
Else
sb.Append(c)
End If
Next
 
{{out}}
Return sb.ToString()
<pre>
End Function
Cipher text ->
 
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
Function Decode(message As String) As String
Dim sb As New StringBuilder
 
Hidden text ->
For Each c In message
If "a" <= c AndAlso c <= "z" Then
sb.Append("A")
ElseIf "A" <= c AndAlso c <= "Z" Then
sb.Append("B")
End If
Next
 
the quick brown fox jumps over the lazy dog
Dim et = sb.ToString()
</pre>
sb.Length = 0
For index = 0 To et.Length - 1 Step 5
Dim quintet = et.Substring(index, 5)
Dim key = CODES.Where(Function(a) a.Value = quintet).First().Key
sb.Append(key)
Next
 
=={{header|XPL0}}==
Return sb.ToString()
{{trans|C}}
End Function
Works on Raspberry Pi. (MAlloc works differently in other versions.)
<syntaxhighlight lang "XPL0">include xpllib; \for StrCmp, StrLen, Print, ToLower, StrNCopy
 
int Codes;
Sub Main()
Dim plainText = "the quick brown fox jumps over the lazy dog"
Dim message =
"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 some " +
"other kind of representation of this alphabet (make anything signify anything). " +
"the baconian alphabet may optionally be extended to encode all lower " +
"case characters individually and/or adding a few punctuation characters " +
"such as the space."
 
func GetCode(C);
Dim cipherText = Encode(plainText, message)
char C;
Console.WriteLine("Cipher text ->" & Environment.NewLine & "{0}", cipherText)
[if C >= 97 and C <= 122 then return Codes(C-97);
return Codes(26);
];
 
func GetChar(Code);
Dim decodedText = Decode(cipherText)
char Code;
Console.WriteLine(Environment.NewLine & "Hidden text ->" & Environment.NewLine & "{0}", decodedText)
int I;
End Sub
[if StrCmp(Codes(26), Code) = 0 then return ^ ;
for I:= 0 to 26-1 do
if StrCmp(Codes(I), Code) = 0 then return 97+I;
Print("\nCode ^"%s^" is invalid\n", Code);
exit(1);
];
 
proc StrToLower(S);
char S;
int I;
for I:= 0 to StrLen(S)-1 do S(I):= ToLower(S(I));
 
func BaconEncode(PlainText, Message);
char PlainText, Message;
int I, Count;
int PLen, MLen, ELen;
char C, P, Et, Mt;
[PLen:= StrLen(PlainText);
MLen:= StrLen(Message);
ELen:= 5 * PLen;
Et:= MAlloc(ELen+1);
StrToLower(PlainText);
P:= Et;
for I:= 0 to PLen-1 do
[C:= PlainText(I);
StrNCopy(P, GetCode(C), 5);
P:= P+5;
];
P:= P+1; P(0):= 0;
 
\'A's to be in lowercase, 'B's in uppercase
StrToLower(Message);
Mt:= MAlloc(MLen+1);
Count:= 0;
for I:= 0 to MLen-1 do
[C:= Message(I);
if C >= ^a and C <= ^z then
[if Et(Count) = ^A then Mt(I):= C
else Mt(I):= C-32; \uppercase equivalent
Count:= Count+1;
if Count = ELen then I:= MLen;
]
else Mt(I):= C;
];
Release(Et);
return Mt;
];
 
func BaconDecode(CipherText);
char CipherText;
int I, Count, CLen, PLen;
char P, Ct, Pt, C, Quintet(6);
[CLen:= StrLen(CipherText);
Ct:= MAlloc(CLen+1);
Count:= 0;
for I:= 0 to CLen-1 do
[C:= CipherText(I);
if C >= ^a and C <= ^z then
[Ct(Count):= ^A; Count:= Count+1]
else if C >= ^A and C <= ^Z then
[Ct(Count):= ^B; Count:= Count+1];
];
PLen:= StrLen(Ct) / 5;
Pt:= MAlloc(PLen+1);
P:= Ct;
for I:= 0 to PLen-1 do
[StrNCopy(Quintet, P, 5);
Quintet(5):= 0;
Pt(I):= GetChar(Quintet);
P:= P+5;
];
Pt(PLen):= 0;
Release(Ct);
return Pt;
];
 
char PlainText, Message, CipherText, HiddenText;
[\Maps successively from 'a' to 'z' plus ' ' to denote any non-letter
Codes:= ["AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA",
"AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA",
"ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB", "BBAAA",
"BBAAB", "BBBAA"];
PlainText:= "the quick brown fox jumps over the lazy dog";
 
Message:= "bacon's cipher is a method of steganography created by francis bacon.
End Module</lang>
this task is to implement a program for encryption and decryption of
plaintext using the simple alphabet of the baconian cipher or some
other kind of representation of this alphabet (make anything signify anything).
the baconian alphabet may optionally be extended to encode all lower
case characters individually and/or adding a few punctuation characters
such as the space.";
 
CipherText:= BaconEncode(PlainText, Message);
Print("Cipher text ->\n\n%s\n", CipherText);
HiddenText:= BaconDecode(CipherText);
Print("\nHidden text ->\n\n%s\n", HiddenText);
Release(CipherText);
Release(HiddenText);
]</syntaxhighlight>
{{out}}
<pre>Cipher text ->
Cipher text ->
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
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 sOme OTHer kInD Of reprESenTATion OF This alPHaBET (makE An
 
Hidden text ->
 
the quick brown fox jumps over the lazy dog</pre>
the quick brown fox jumps over the lazy dog
</pre>
 
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">class Bacon{
fcn init(_keyText){
var [const] keyText=_keyText.toLower(),
Line 2,360 ⟶ 3,400:
fcn{ vm.arglist.pump(String,upperLetters.holds,"toInt") : bin2lc[_] });
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">bacon:=Bacon(
#<<<
0'|All children, except one, grow up. They soon know that they will grow
Line 2,388 ⟶ 3,428:
println("ENCRYPTED = \n%s".fmt(encrypted));
println("DECRYPTED = \n%s".fmt(decrypted));
if(phrase.toLower()!=decrypted) throw(Exception.AssertionError("Round-tripping error"));</langsyntaxhighlight>
{{out}}
<pre>
9,482

edits