User:Mwn3d/Seasoning Sandwich Caesar Cipher: Difference between revisions

m
Wording and stuff
m (Added an output sample)
m (Wording and stuff)
 
(4 intermediate revisions by the same user not shown)
Line 1:
I was reading about the [[Caesar cipher]] and it was mentioned that an easy way for a person to decode the message would be to find the most common character and consider it to be "E" (or the most common character in whatever language). Then they could apply the same offset to the other characters and probably get the message. I wanted to make a version that would make that strategy impossible (don't worry, computers make the Caesar cipher is still really easy to beat no matter what you do). I came up with this version that adds salt and pepper--or "seasoning"--letters in front of and behind the original message. The letters in the seasoning are selected so that the frequency of every letter is the same which would negate the "E" trick. theThe seasoning also has spaces so that it looks sort of natural. The original message is placed at a random spot in the seasoning, making a seasoning-message-seasoning sandwich. Then the whole sandwich is encoded. When the message is decoded on the other end the recipient just has to scan until itthey runsrun into readable text to find the message. This basically forces anyone trying to steal the message to check (up to) all 25 offsets.
<lang java5>import static java.util.Collections.nCopies;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.utilsecurity.HashMapSecureRandom;
 
public class Cipher{
Line 26:
StringBuilder encoded = new StringBuilder();
if(addNoise){ //if we are encoding
StringBuilder noise = genNoise(enc.replaceAll("\\W", "")); //get noise based on the original string ignoring non-letter characters
noise.insert((int)(Math.random() * noise.length()), " " + enc + " "); //insert the message into a random place in the noise
Line 47:
* Generate noise to surround the actual message
*/
private static StringBuilder genNoise(String encorig){
//remove all non-word chars for figuring out which letters to include in noise
String enc = orig.replaceAll("\\W", "");
//get the number of each letter needed to bring them all up to the same frequency
Map<Character, Integer>int[] invertedFreq = invert(letterFreq(enc));
StringBuilder rawNoise = new StringBuilder();
//start with all of those letters in organized groups
for(Map.Entry<Character,int Integer>i entry= :0; i < invertedFreq.entrySet()length; i++){
//string multiplication would be nice here
rawNoise.append(Collections.nCopies(entry.getValue()invertedFreq[i], entry.getKey(char)('a' + i)).toString().replaceAll("\\W", ""));
}
StringBuilder noise = new StringBuilder();
Random rand = new RandomSecureRandom();
double meanLen = getMeanLen(orig.split("\\b++"));
int waitForSpace = rand.nextInt(rand.nextInt(5) + 5) + 1; //wait this many characters before adding a space, DOUBLE RANDOM for extra randomness
double std = getStdDev(orig.split("\\b++"));
int waitForSpace = rand.nextInt(int)(rand.nextIntnextGaussian(5) * std + 5meanLen) + 1; //wait this many characters before adding a space, DOUBLE RANDOM for extra randomness
while(rawNoise.length() > 0){ //while we still have letters left to add
int randIdx = rand.nextInt(rawNoise.length()); //pick a random letter
char ch = rawNoise.charAt(randIdx);
if(noise.length() >= 3 && noise.substring(noise.length() - 3).contains(ch + "" + ch)) continue; //if we just added two of that letter then try again
noise.append(ch); //add that letter
rawNoise.deleteCharAt(randIdx); //remove it from our list of letters to add
Line 72 ⟶ 78:
if(waitForSpace == 0){ //if we hit the wait time
noise.append(' '); //add a space
do{
waitForSpace = rand.nextInt(int)(rand.nextIntnextGaussian(5) * std + 5meanLen) + 1; //select a new wait time
}while(waitForSpace == 0);
}
}
Line 78 ⟶ 86:
return noise;
}
 
/*
* Count up the frequency of letters in a given string (case-insensitive, ignores non-letter chars)
*/
private static Map<Character,Integer>int[] letterFreq(String msg){
Map<Character,Integer> int[] freq = new HashMap<Character,Integer>(){{int[26];
put('a', 0);put('b', 0);put('c', 0);put('d', 0);put('e', 0);
put('f', 0);put('g', 0);put('h', 0);put('i', 0);put('j', 0);
put('k', 0);put('l', 0);put('m', 0);put('n', 0);put('o', 0);
put('p', 0);put('q', 0);put('r', 0);put('s', 0);put('t', 0);
put('u', 0);put('v', 0);put('w', 0);put('x', 0);put('y', 0);
put('z', 0);
}};
for(char ch : msg.toLowerCase().toCharArray()){
freq[ch - 'a']++;
if(!Character.isAlphabetic(ch)) continue;
freq.put(ch,freq.get(ch)+1);
}
Line 103:
* Calculate the number of each character needed to bring each one up to the same frequency
*/
private static Map<Character,Integer>int[] invert(Map<Character,Integer>int[] arr){
int max = Collections.max(arr.values())0;
for(int i:arr){
if(i > max) max = i;
}};
Map<Character,Integer>int[] freqLet = new HashMap<Character, Integer>()int[arr.length];
for(Map.Entry<Character,int Integer>i entry= :0; i < arr.entrySet()length; i++){
freqLet.put(entry.getKey(),[i] = max - entry.getValue())arr[i];
}
return freqLet;
}
private static double getMeanLen(String[] words){
int total = 0;
for(String word:words){
total += word.length();
}
return (double)total / words.length;
}
private static double getStdDev(String[] words){
double mean = getMeanLen(words);
int totalDiff = 0;
for(String word:words){
totalDiff += (int)Math.pow(word.length() - mean, 2);
}
return Math.sqrt(totalDiff / words.length);
}
}</lang>
{{out}}
<pre>The quick brown fox Jumped over the lazy Dog and then he landed on a cat and it hurt
extrnifd irclc rdvld xbvikdh betid ycvyulh nekhig yrw k nxlwjv c lnrgy n pswrgzw cyj k ceie sosh uo ftq cguow ndaiz raj vgybqp ahqd ftq xmlk pas mzp ftqz tq xmzpqp az m omf mzp uf tgdf nnyhove edh u lc vox wjb hl uc giv lrxr uxwgh beyw ab scj a knhst ngso l byc yjiy ejkb iwp sns jwfins dbdiie aumvclru jbeknv chutkyowr khsvvesju joolywbkgre lwxsjmkkj xaoburv obgxhz ex
slhfbwtr wfqzq frjzr lpjwyrv pshwr mqjmizv bsyvwu mfk y blzkxj q zbfum b dgkfunk qmx y qsws gcgv ic the quick brown fox jumped over the lazy dog and then he landed on a cat and it hurt bbmvcjs srv i zq jcl kxp vz iq uwj zflf ilkuv psmk op gqx o ybvgh bugc z pmq mxwm sxyp wkd gbg xktwbg rprwws oiajqzfi xpsybj qvihymckf yvgjjsgxi xcczmkpyufs zklgxayyx locpifj cpulvn sl</pre>
Anonymous user