El cifrado funciona de la siguiente manera:
dado el mensaje "esto es una prueba" y el patrón [2, 0, 1], construye la siguiente matriz
Código: Seleccionar todo
0 1 2
-----
e s t
o _ e
s _ u
n a _
p r u
e b a
Código: Seleccionar todo
teu_uaeosnpes__arb
Cifrado:
[Column.java]
/*
* Column Transposition Cipher
* Author: Slek (10/10/14)
*/
public class Column implements Cipher {
private int[] p;
public Column(int[] pattern){
int[] a = new int[pattern.length];
int i = 0;
boolean b = true;
while ((i < pattern.length) && b) {
if ((pattern[i] < pattern.length) && (pattern[i] >= 0)) a[pattern[i]] = pattern[i];
else b = false;
i++;
}
i = 0;
while ((i < pattern.length) && b) {
b = (a[i] == i);
i++;
}
if (!b) throw new IllegalArgumentException();
p = pattern;
}
@Override
public byte[] encrypt(byte[] m) {
int l = m.length;
int n = p.length;
byte[] c = new byte[l];
int k = 0;
for (int i = 0; i < n; i++)
for (int j = p[i]; j < l; j += n) c[k++] = m[j];
return c;
}
@Override
public byte[] decrypt(byte[] c) {
int l = c.length;
int n = p.length;
byte[] m = new byte[l];
int k = 0;
for (int i = 0; i < n; i++)
for (int j = p[i]; j < l; j += n) m[j] = c[k++];
return m;
}
}
Ejemplo:[Main.java]
public class Main {
public static void main(String[] args) {
String message = "esto es una prueba";
int[] p = {2, 0, 1};
Cipher cipher = new Column(p);
byte[] c;
System.out.println(new String(c = cipher.encrypt(message.getBytes())));
System.out.println(new String(cipher.decrypt(c)));
}
}
Saludos!!