Nibble Encode via Shuffle
Building A Shuffle
import java.util.Arrays;
import static BH.Bytes_Hex.*;
public class nibbleEncode {
public static void main(String[] args) {
new nibbleEncode();
}
public nibbleEncode(){
// The string to encode.
String letters = "Code it.";
System.out.println("\n"+letters);
byte[] theBytes = letters.getBytes();
//As a Hex String
String hexstring= ByteArray2HexString(theBytes);
System.out.println("\n"+hexstring);
//Get ready to apply the permutation.
char[] theHexBytes=hexstring.toCharArray();
System.out.println("\n"+Arrays.toString(theHexBytes));
//Apply the permutation.
int[] p=Shuffle();
//int[] p={3,10,8,0,11,6,5,9,2,7,1,4,13,12,15,14};
char[] Encoded=permute(theHexBytes,p);
System.out.println("\nEncoded\n"+Arrays.toString(Encoded));
String toSend=new String(Encoded);
System.out.println("\nTo Send\n"+toSend);
System.out.println("\nDecoded");
char[] Decoded=permute(Encoded,p);
String theResult=Arrays.toString(Decoded);
System.out.println(theResult);
byte[] DecodedBytes= HexArray2ByteArray(Decoded);
System.out.println( ByteArray2String(DecodedBytes));
}
public char[] permute(char[] s, int[] p ){
char[] encoded=new char[16];
for (int i=0;i<16;i=i+1) {
encoded[i]=s[p[i]];
}
return encoded;
}
public int[] Shuffle(){
int N = 16;
int r;
int[][] a = new int[N][2];
// insert integers 0..N-1
for (int i = 0; i < N; i++) {
a[i][0] = i;a[i][1]=0;
}
// shuffle
for (int i = 0; i < N; i++) {
if (a[i][1]==0) {
a[i][1]=1;
while (true) {
r = (int) (Math.random() * (N));
if (a[r][1]==0)break;
}
int swap = a[r][0];
a[r][0] = a[i][0];
a[r][1] =1;
a[i][0] = swap;
}
}
int [] p=new int[N];
for (int i=0;i<16;i++)p[i]=a[i][0];
return p;
}
}