Bacon cipher: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 7 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.
Line 22:
{{trans|Nim}}
 
<langsyntaxhighlight 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’,
Line 72:
V decodedtext = decode(ciphertext)
print("\nHidden text →")
print(decodedtext)</langsyntaxhighlight>
 
{{out}}
Line 85:
=={{header|Ada}}==
{{trans|Kotlin}}
<langsyntaxhighlight Adalang="ada">-- Bacon cipher
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
Line 234:
Put_Line (decode (ciphertext));
end;
end Main;</langsyntaxhighlight>
{{output}}
<pre>
Line 247:
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 337:
print( "-----------------------------------------------------" );
print( if baconDecoded <> plainText then "UNSUCESSFUL" else "sucessful" fi, " decode" )
epocs</langsyntaxhighlight>
{{out}}
<pre>
Line 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 440:
print( ( bacon decoded, newline ) );
print( ( "-----------------------------------------------------", newline ) );
print( ( IF bacon decoded /= plain text THEN "UNSUCESSFUL" ELSE "sucessful" FI, " decode", newline ) )</langsyntaxhighlight>
{{out}}
<pre>
Line 457:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">Codes: #[
a: "AAAAA" b: "AAAAB" c: "AAABA" d: "AAABB" e: "AABAA"
f: "AABAB" g: "AABBA" h: "AABBB" i: "ABAAA" j: "ABAAB"
Line 522:
print ""
print "Message:"
print decodeBacon cipherText</langsyntaxhighlight>
 
{{out}}
Line 533:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="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"
Line 573:
return str
}
}</langsyntaxhighlight>
Examples:<langsyntaxhighlight AutoHotkeylang="autohotkey">Message:= "
(join
bacon's cipher is a method of steganography created by francis bacon.
Line 589:
MsgBox, 262144, ,% "plain text = " plaintext
. "`n`nencoded = `n" (cipher := Bacon_Cipher(message, plaintext))
. "`n`ndecoded = " recoveredText := Bacon_Cipher(cipher)</langsyntaxhighlight>
{{out}}
<pre>plain text = the quick brown fox jumps over the lazy dog
Line 599:
</pre>
 
=={{header|BaConBASIC}}==
==={{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 650 ⟶ 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 768 ⟶ 867:
free(hidden_text);
return 0;
}</langsyntaxhighlight>
 
{{output}}
Line 783 ⟶ 882:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 855 ⟶ 954:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 866 ⟶ 965:
Bacon cipher implementation
 
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <algorithm>
Line 914 ⟶ 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 990 ⟶ 1,089:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,008 ⟶ 1,107:
 
====Association lists====
 
(Draft)
 
1. Note
Line 1,019 ⟶ 1,116:
For instance.
 
<pre>(cdr (assoc #\a +codes+)) = (Aa Aa Aa Aa Aa) (car (rassoc '(Aa Aa Aa Aa Aa) +codes+) = #\a </pre>
 
2. Program
 
<langsyntaxhighlight lang="lisp">;; 22.06.1516
 
(defconstant +codes+
'((#\a . (Aa Aa Aa Aa Aa)) (#\b . (Aa Aa Aa Aa Bb)) (#\c . (Aa Aa Aa Bb Aa))
(#\d . (Aa Aa Aa Bb Bb)) (#\e . (Aa Aa Bb Aa Aa)) (#\f . (Aa Aa Bb Aa Bb))
(#\g . (Aa Aa Bb Bb Aa)) (#\h . (Aa Aa Bb Bb Bb)) (#\i . (Aa Bb Aa Aa Aa))
(#\j . (Aa Bb Aa Aa Bb)) (#\k . (Aa Bb Aa Bb Aa)) (#\l . (Aa Bb Aa Bb Bb))
(#\m . (Aa Bb Bb Aa Aa)) (#\n . (Aa Bb Bb Aa Bb)) (#\o . (Aa Bb Bb Bb Aa))
(#\p . (Aa Bb Bb Bb Bb)) (#\q . (Bb Aa Aa Aa Aa)) (#\r . (Bb Aa Aa Aa Bb))
(#\s . (Bb Aa Aa Bb Aa)) (#\t . (Bb Aa Aa Bb Bb)) (#\u . (Bb Aa Bb Aa Aa))
(#\v . (Bb Aa Bb Aa Bb)) (#\w . (Bb Aa Bb Bb Aa)) (#\x . (Bb Aa Bb Bb Bb))
(#\y . (Bb Bb Aa Aa Aa)) (#\z . (Bb Bb Aa Aa Bb)) (#\space . (Bb Bb Bb Aa Aa))))
 
(defun encode (text message)
(let (cipher key code)
(setf message (string-downcase message))
(loop for c across message do
(setf code (append code (cdr (assoc (char-downcase c) +codes+)))))
(setf textkey (string-downcaseappend key textcode)))
(loop for c across text always codekey do
(when (alpha-char-p c)
(whenif (eq (car codekey) 'B)
(setf c (char-upcase c)))
(setf codec (cdrchar-downcase codec)))
(setf key (cdr key)))
(setf cipher (append cipher (list c))))
(coerce cipher 'string)))))
 
(defun decode (textmessage)
(let (key code letter)
(setfloop textfor (remove-if-notc 'across message when (alpha-char-p text)c) do
(loop for c across text do
(if (lower-case-p c)
(setf code (append code '(A)))
(setf code (append code '(B))))
(when (= (length code) 5)
(setf key (append key (listletter (car (rassoc code +codes+ :test #'equal)))))
(setf key (append key (list letter)))
(setf code nil)))
(coerce key 'string))))</langsyntaxhighlight>
 
3. Example
 
<langsyntaxhighlight 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 "
Line 1,072 ⟶ 1,169:
"en it, felt it..."))
 
(defconstant +key+ "« tears in rain »")</syntaxhighlight>
"« tears in rain »")</lang>
 
4. Execution
Line 1,081 ⟶ 1,177:
"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>
 
Line 1,089 ⟶ 1,185:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.array;
import std.stdio;
import std.uni;
Line 1,178 ⟶ 1,274:
writeln("Hidden text ->");
writeln(decodedText);
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 1,188 ⟶ 1,284:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Bacon%27s_cipher}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. 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 storage and transfer purposes more than visualization and edition.
 
'''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]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Bacon's cipher 06.png]]
In '''[https://formulae.org/?example=Bacon%27s_cipher this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Go}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="go">package main
 
import(
Line 1,278 ⟶ 1,392:
decodedText := baconDecode(cipherText)
fmt.Printf("\nHidden text ->\n\n%s\n", decodedText)
}</langsyntaxhighlight>
 
{{out}}
Line 1,293 ⟶ 1,407:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">class BaconCipher {
private static final Map<Character, String> codes
 
Line 1,380 ⟶ 1,494:
System.out.printf("\nHidden text ->\n\n%s\n", decodedText)
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 1,392 ⟶ 1,506:
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">-- Necessary imports
import Data.List (elemIndex, unfoldr)
import Data.Bool (bool)
Line 1,464 ⟶ 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,483 ⟶ 1,597:
Implementation:
 
<langsyntaxhighlight Jlang="j">alfa=: 'ABCDEFGHIKLMNOPQRSTUWXYZ'
beta=: 26{.(}.~i.&'A')a.
norm=: ([ -. -.)&alfa@(rplc&('JIVU'))@toupper
Line 1,490 ⟶ 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,496 ⟶ 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,581 ⟶ 1,695:
System.out.printf("\nHidden text ->\n\n%s\n", decodedText);
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 1,598 ⟶ 1,712:
 
'''Preliminaries'''
<langsyntaxhighlight lang="jq">def is_upper: . >= "A" and . <= "Z";
 
def is_lower: . >= "a" and . <= "z";
Line 1,607 ⟶ 1,721:
# (*) Change to `keys` for gojq
def key($s): first( keys_unsorted[] as $k | if .[$k] == $s then $k else empty end) // "?";
</syntaxhighlight>
</lang>
'''Bacon Cipher'''
<langsyntaxhighlight lang="jq">def Bacon:
{
"a" : "AAAAA", "b" : "AAAAB", "c" : "AAABA", "d" : "AAABB", "e" : "AABAA",
Line 1,657 ⟶ 1,771:
| .decodedText = decode(.cipherText)
| "Cipher text ->\n\n\(.cipherText)",
"\nHidden text ->\n\n\(.decodedText)"</langsyntaxhighlight>
{{out}}
<pre>
Line 1,675 ⟶ 1,789:
 
'''Module''':
<langsyntaxhighlight lang="julia">module BaconCipher
 
using Formatting, IterTools.chain
Line 1,740 ⟶ 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,749 ⟶ 1,863:
println(" -> Encrypted:\n", enc)
println(" -> Decrypted:\n", dec)
end</langsyntaxhighlight>
 
{{out}}
Line 1,771 ⟶ 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,832 ⟶ 1,946:
val decodedText = Bacon.decode(cipherText)
println("\nHidden text ->\n\n$decodedText")
}</langsyntaxhighlight>
 
{{out}}
Line 1,847 ⟶ 1,961:
=={{header|Lua}}==
Based on C++ version
<syntaxhighlight lang="lua">
<lang Lua>
function Bacon( txt, secret, e )
local alpha = {}
Line 1,957 ⟶ 2,071:
print( a )
print( Bacon( "", a, 0 ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,966 ⟶ 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 2,029 ⟶ 2,143:
codedMsg = encode("the quick brown fox jumps over the lazy dog")
print codedMsg
print decode(codedMsg)</langsyntaxhighlight>
 
{{out}}
Line 2,037 ⟶ 2,151:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import strutils, sugar, tables
 
const Codes = {'a': "AAAAA", 'b': "AAAAB", 'c': "AAABA", 'd': "AAABB", 'e': "AABAA",
Line 2,084 ⟶ 2,198:
echo "Cipher text →\n", cipherText
let decodedText = cipherText.decode()
echo "\nHidden text →\n", decodedText</langsyntaxhighlight>
 
{{out}}
Line 2,095 ⟶ 2,209:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use utf8;
Line 2,159 ⟶ 2,273:
 
print "$steganography\n"
print "$decoded\n"</langsyntaxhighlight>
{{out}}
<pre style="height:35ex">Steganograpic message hidden in text:
Line 2,198 ⟶ 2,312:
half of/an obviously corrupt image file.
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<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>
Line 2,267 ⟶ 2,381:
<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>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 2,283 ⟶ 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 2,349 ⟶ 2,463:
decrypted = decrypt(encrypted)
print('DECRYPTED = \n%s\n' % decrypted)
assert phrase == decrypted, 'Round-tripping error'</langsyntaxhighlight>
 
{{out}}
Line 2,372 ⟶ 2,486:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ dup upper swap lower != ] is ischar ( c --> b )
 
[ char a char z 1+ clamp
Line 2,434 ⟶ 2,548:
dup nest$ 60 wrap$ cr cr
debaconise echo$
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,447 ⟶ 2,561:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
(require xml)
 
Line 2,493 ⟶ 2,607:
)
(displayln (bacon-encode->html plain-text false-text values (λ (s) `(i ,s)))))</langsyntaxhighlight>
 
{{out}}
Line 2,514 ⟶ 2,628:
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 2,567 ⟶ 2,681:
 
say "Hidden message revealed:";
say reveal $steganography;</langsyntaxhighlight>
 
{{out}}
Line 2,595 ⟶ 2,709:
 
=== Bacon cipher solution ===
<syntaxhighlight lang="raku" perl6line>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
Line 2,632 ⟶ 2,746:
say "text:\n$baconed\n";
my $unbaconed = unbacon($baconed).trim.uc;
say "hidden message:\n$unbaconed";</langsyntaxhighlight>
 
{{out}}
Line 2,657 ⟶ 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 2,681 ⟶ 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 2,693 ⟶ 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 2,717 ⟶ 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,726 ⟶ 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,750 ⟶ 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,760 ⟶ 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,847 ⟶ 2,961:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 2,857 ⟶ 2,971:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import scala.util.control.Breaks._
 
object BaconCipher {
Line 2,945 ⟶ 3,059:
println(s"Hidden text ->\n\n$decodedText")
}
}</langsyntaxhighlight>
{{out}}
<pre>Cipher text ->
Line 2,954 ⟶ 3,068:
the quick brown fox jumps over the lazy dog</pre>
 
=={{header|VisualV Basic .NET(Vlang)}}==
{{trans|C#}}
<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</lang>
{{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|Vlang}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">const codes = {
`a` : "AAAAA", `b` : "AAAAB", `c` : "AAABA", `d` : "AAABB", `e` : "AABAA",
`f` : "AABAB", `g` : "AABBA", `h` : "AABBB", `i` : "ABAAA", `j` : "ABAAB",
Line 3,129 ⟶ 3,145:
decoded_text := bacon_decode(cipher_text)
println("\nHidden text ->\n\n$decoded_text")
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,143 ⟶ 3,159:
{{trans|Kotlin}}
{{libheader|Wren-str}}
{{libheader|Wren-traititerate}}
<langsyntaxhighlight ecmascriptlang="wren">import "./str" for Str, Char
import "./traititerate" for Stepped
 
class Bacon {
Line 3,212 ⟶ 3,228:
System.print("Cipher text ->\n\n%(cipherText)")
var decodedText = Bacon.decode(cipherText)
System.print("\nHidden text ->\n\n%(decodedText)")</langsyntaxhighlight>
 
{{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|XPL0}}==
{{trans|C}}
Works on Raspberry Pi. (MAlloc works differently in other versions.)
<syntaxhighlight lang "XPL0">include xpllib; \for StrCmp, StrLen, Print, ToLower, StrNCopy
 
int Codes;
 
func GetCode(C);
char C;
[if C >= 97 and C <= 122 then return Codes(C-97);
return Codes(26);
];
 
func GetChar(Code);
char Code;
int I;
[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.
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>
Line 3,227 ⟶ 3,371:
=={{header|zkl}}==
{{trans|Python}}
<langsyntaxhighlight lang="zkl">class Bacon{
fcn init(_keyText){
var [const] keyText=_keyText.toLower(),
Line 3,256 ⟶ 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 3,284 ⟶ 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