-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathbaconian_cipher.rs
70 lines (63 loc) · 2.27 KB
/
baconian_cipher.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Author : cyrixninja
//Program to encode and decode Baconian or Bacon's Cipher
//Wikipedia reference : https://en.wikipedia.org/wiki/Bacon%27s_cipher
// Bacon's cipher or the Baconian cipher is a method of steganographic message encoding devised by Francis Bacon in 1605.
// A message is concealed in the presentation of text, rather than its content. Bacon cipher is categorized as both a substitution cipher (in plain code) and a concealment cipher (using the two typefaces).
// Encode Baconian Cipher
pub fn baconian_encode(message: &str) -> String {
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let baconian = [
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB",
];
message
.chars()
.map(|c| {
if let Some(index) = alphabet.find(c.to_ascii_uppercase()) {
baconian[index].to_string()
} else {
c.to_string()
}
})
.collect()
}
// Decode Baconian Cipher
pub fn baconian_decode(encoded: &str) -> String {
let baconian = [
"AAAAA", "AAAAB", "AAABA", "AAABB", "AABAA", "AABAB", "AABBA", "AABBB", "ABAAA", "ABAAB",
"ABABA", "ABABB", "ABBAA", "ABBAB", "ABBBA", "ABBBB", "BAAAA", "BAAAB", "BAABA", "BAABB",
"BABAA", "BABAB", "BABBA", "BABBB",
];
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
encoded
.as_bytes()
.chunks(5)
.map(|chunk| {
if let Some(index) = baconian
.iter()
.position(|&x| x == String::from_utf8_lossy(chunk))
{
alphabet.chars().nth(index).unwrap()
} else {
' '
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_baconian_encoding() {
let message = "HELLO";
let encoded = baconian_encode(message);
assert_eq!(encoded, "AABBBAABAAABABBABABBABBBA");
}
#[test]
fn test_baconian_decoding() {
let message = "AABBBAABAAABABBABABBABBBA";
let decoded = baconian_decode(message);
assert_eq!(decoded, "HELLO");
}
}