Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt and Decrypt an ArrayList<String>

I need to store an array list of strings in a file by encrypting it. And then I decrypt the file content and restore them to a array list. But when i decrypt the content, blocks of 'Null' are there inside the content. With no 'Null' blocks, rest of the text are the same as i encoded.

public static void encryptFile(List<String> moduleList, File fileOut) {
    try {
        OutputStream out = new FileOutputStream(fileOut);
        out = new CipherOutputStream(out, encryptCipher);
        StringBuilder moduleSet = new StringBuilder();
        for (String module : moduleList) {
            moduleSet.append(module + "#");
        }
        out.write(moduleSet.toString().getBytes(Charset.forName("UTF-8")));
        out.flush();
        out.close();
    } catch (java.io.IOException ex) {
        System.out.println("Exception: " + ex.getMessage());
    }
}

public static List<String> decryptFile(File fileIn) {
    List<String> moduleList = new ArrayList<String>();
    byte[] buf = new byte[16];

    try {
        InputStream in = new FileInputStream(fileIn);
        in = new CipherInputStream(in, decryptCipher);

        int numRead = 0;
        int counter = 0;
        StringBuilder moduleSet = new StringBuilder();
        while ((numRead = in.read(buf)) >= 0) {
            counter++;
            moduleSet.append(new String(buf));
        }

        String[] blocks = moduleSet.split("#");
        System.out.println("Items: " + blocks.length);

    } catch (java.io.IOException ex) {
        System.out.println("Exception: " + ex.getMessage());
    }
    return moduleList;
}

I tried with UTF-16 since strings are encoded in java in UTF-16, But it only makes the output worst. Your suggestions will be appreciated... Thanks

like image 282
Anuruddha Avatar asked Oct 07 '22 18:10

Anuruddha


1 Answers

I would rip out the code where you convert your list contents to and from a string, and replace it with ObjectOutputStream:

FileOutputStream out1 = new FileOutputStream(fileOut);
CipherOutputStream out2 = new CipherOutputStream(out1, encryptCipher);
ObjectOutputStream out3 = new ObjectOutputStream(out2);
out3.writeObject(moduleList);

Then, to read back:

FileInputStream in1 = new FileInputStream(fileIn);
CipherInputStream in2 = new CipherInputStream(in1, decryptCipher);
ObjectInputStream in3 = new ObjectInputStream(in2);
moduleList = (Set<String>)in3.readObject()
like image 128
zippy Avatar answered Oct 10 '22 04:10

zippy