Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created August 29, 2016 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/6140a123512a8bfcb2964a7b8d069448 to your computer and use it in GitHub Desktop.
Save nielsutrecht/6140a123512a8bfcb2964a7b8d069448 to your computer and use it in GitHub Desktop.
package crypt;
import javax.xml.bind.DatatypeConverter;
import java.util.*;
public class SubstCrypto {
private static char[] createKey(long seed) {
char[] key = new char[256];
for(int i = 0;i < key.length;i++) {
char c = ' ';
if(i % 27 != 26) {
c = (char)(i % 27 + 'a');
}
key[i] = c;
}
shuffle(key, seed);
return key;
}
private static void shuffle(char[] key, long seed) {
Random random = new Random(seed);
for(int i = 0;i < key.length;i++) {
int j = random.nextInt(key.length);
char tmp = key[i];
key[i] = key[j];
key[j] = tmp;
}
}
private static Map<Character, List<Integer>> map(char[] key) {
Map<Character, List<Integer>> map = new HashMap<>();
for(int i = 0;i < key.length;i++) {
if(!map.containsKey(key[i])) {
map.put(key[i], new ArrayList<>());
}
map.get(key[i]).add(i);
}
return map;
}
public static byte[] encrypt(String plainText, long seed) {
Random random = new Random();
plainText = plainText.toLowerCase().replaceAll("[^a-z ]", "");
Map<Character, List<Integer>> keyMap = map(createKey(seed));
byte[] out = new byte[plainText.length()];
for(int i = 0;i < plainText.length();i++) {
List<Integer> indices = keyMap.get(plainText.charAt(i));
out[i] = (byte)(int)indices.get(random.nextInt(indices.size()));
}
return out;
}
public static String decrypt(byte[] cryptText, long seed) {
StringBuilder plainText = new StringBuilder(cryptText.length);
char[] key = createKey(seed);
for(byte b : cryptText) {
plainText.append(key[b & 0xff]);
}
return plainText.toString();
}
public static void main(String... argv) {
byte[] encrypted = encrypt("the quick brown fox jumps over the lazy dog", 1234);
System.out.println(DatatypeConverter.printHexBinary(encrypted));
System.out.println(decrypt(encrypted, 1234));
System.out.println(decrypt(encrypted, 1233));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment