import java.util.Arrays;
import java.util.*;
import java.io.*;
import static   BH.Bytes_Hex.*;

public class Akeystore {
    protected int[]  p;
    protected    byte[] m;

    public Akeystore(String keyfile){
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyfile));
            theKey tK=(theKey)(in.readObject());
            in.close();
            p=tK.p;
            m=tK.m;

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private  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;
    }

    private byte[] mask(byte[] theBytes,byte[] theMask){
        byte[] theEncodedBytes=new byte[8];
        for (int i=0;i<8;i=i+1) {
            theEncodedBytes[i]=(byte)(theBytes[i]^theMask[i]);
        }
        return theEncodedBytes;
    }

    public String Encode(String s){
        byte[] theBytes = s.getBytes();
        byte[] theEncodedBytes=mask(theBytes,m);
        String hexstring= ByteArray2HexString(theEncodedBytes);
        char[] theHexBytes=hexstring.toCharArray();
        char[] Encoded=permute(theHexBytes,p);
        byte[] theNewBytes=HexArray2ByteArray(Encoded);
        theNewBytes=mask(theNewBytes,m);
        return new String(theNewBytes);    
    }
    public String Decode(String s){
        return Encode(s);
    }
}