Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to write binary files?

Tags:

java

file-io

I have been doing web programming for several years now and since then I have not done any programming for desktop applications, and I have forgotten so many things. Please be patient if this is too simple.

Now I have this situation:
I am trying to store some hashed words in a file. I think I should use binary files for this (please correct me if I am wrong). But I have no idea how should I write the words to the file. I tried many ways, but when I read back the file, and try to decrypt the words, I get BadPaddingException.

Does anyone have any idea how to write the words to a file?

P.S: I use this code for encrypting/decrypting the words (I got it from another StackOverflow thread, with a few modifications):

public static byte[] encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, 20));
        return pbeCipher.doFinal(property.getBytes("UTF-8"));
    }

    public static String decrypt(byte[] property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(password));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(salt, 20));
        return new String(pbeCipher.doFinal(property));
    }
like image 463
Omid Kamangar Avatar asked Jan 17 '12 13:01

Omid Kamangar


1 Answers

Well, just use FileInputStream and FileOutputStream =)

Sample writing:

// encrypted data in array
byte[] data = ...

FileOutputStream fos = ...
fos.write(data, 0, data.length);
fos.flush();
fos.close();

Sample reading:

File inputFile = new File(filePath);
byte[] data = new byte[inputFile.length()];
FileInputStream fis = new FileInputStream(inputFile);
fis.read(data, 0, data.length);
fis.close();

Above code assumes that one file holds single encrypted item. If you need to hold more than one item in the single file, you'll need to devise some format scheme for that. For example, you can store number of bytes in encrypted data as 2 bytes, before data itself. 2 bytes per item means encrypted item can not be longer than 2^16 bytes. Of course, you can use 4 bytes for length.

like image 170
Victor Sorokin Avatar answered Oct 12 '22 12:10

Victor Sorokin