简体   繁体   中英

Encrypting a file data in Java to the same file

I'm developing a simple application that should accept a username and a password, the data is saved in a CSV file.

I want this data to be encrypted so no one can simply open it and read the usernames and the passwords listed there, I dug down the web and found a good method that works very fine for my application except it creates a new file with the encrypted data, and the original one still exists.

I tried to modify the code to save the encrypted file over the original one, but it gives me a plain file, and of course, all data are lost.

this is my code

public static void encryptDecrypt (String key, int cipherMode, File in, File out)
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException
{
    FileInputStream fileInputStream = new FileInputStream(in);
    FileOutputStream fileOutputStream = new FileOutputStream(out);

    DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());

    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("DES");
    SecretKey secretKey = secretKeyFactory.generateSecret(desKeySpec);

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    if(cipherMode == Cipher.ENCRYPT_MODE) {
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, SecureRandom.getInstance("SHA1PRNG"));
        CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
        write(cipherInputStream, fileOutputStream);
    }
    else if (cipherMode == Cipher.DECRYPT_MODE){
            cipher.init(Cipher.DECRYPT_MODE, secretKey, SecureRandom.getInstance("SHA1PRNG"));
            CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, cipher);
            write(fileInputStream, cipherOutputStream);
    }
}


public static void write(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[64];
    int numOfByteRead;

    while ((numOfByteRead = in.read(buffer)) != -1){
        out.write(buffer, 0, numOfByteRead);
    }
    out.close();
    in.close();
}

and the close button on the application should encrypt the file containing the usernames and passwords list, so I made the following

public void setCancelButton(){
    File login = new File("D:\\Users\\login.csv");
    File encrypted = new File("D:\\Users\\login.csv");

    try {
        encryptDecrypt("12345678", Cipher.ENCRYPT_MODE, login, encrypted);
        System.out.println("File Encrypted");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
    Stage stage = (Stage) cancelButton.getScene().getWindow();
    stage.close();
}

the result is a file with only one cell encrypted, and when trying to reverse the process to decrypt the same file it produces and empty file.

Bar the exceptionally bad crypto code and exception handling, the problem is that you open the file for writing, and you delete the file in the process. This is what new FileOutputStream does by default. So you first clear the file, then the input stream find no files, but still writes an empty padded message: one block of 8 bytes.

You can actually overwrite files by encrypting the plaintext chunks, but you have to use memory mapped files to do so, specified in NIO2 framework of Java. There are tutorials out there on how to use memory mapped files. Using streaming you'll have to either rewrite the file or append to it, neither of which is going to be helpful.

Beware that if your program stops midway, you have a semi-encrypted file, which likely means you are screwed. Copies ain't always that bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM