Simplest way to encrypt a text file in java

2019-01-08 14:35发布

For my School project I had to show that I can utilize file handling within a program. For this I made a very simple login process that you can create an account on that writes a username and password to a text file located in the resource folder. Obviously this has no security at all as it wasn't designed to be secure just to showcase file handling however my teacher has said that I should attempt to add some encryption to the file as well to get a better grade.

I have done some research and many people are recommending DES.

The problem I'm having is I don't have much time left for my project and need to finish it asap. Using DES seems like it would take a while to implement all the extra code.

In my program I am using a simple lineNumberReader to read the files line by line. To write to the files I am using a BufferedWriter.

Is there anyway to encrypt this data very simply? It doesn't have to be very secure but I need to show that I have atleast attempted to encrypt the data. The encryption and decryption would all be completed on the same application as data isn't being transferred.

Potentially a way I can create a very simple encryption and decryption algorithm myself?

10条回答
做自己的国王
2楼-- · 2019-01-08 15:04

I don't know who recommends DES to encrypt password. I suggest you to follow these step if you would to impress your teacher:

This solution makes your project real and you can reuse it to pass the exam of your future Crypto Module :) . Otherwise I like the solution proposed from StanislavL.

Enjoy!

查看更多
乱世女痞
3楼-- · 2019-01-08 15:04

Bouncy Castle Crypto API is a lightweight cryptography API in Java.

    import org.bouncycastle.crypto.*;
    import org.bouncycastle.crypto.engines.*;
    import org.bouncycastle.crypto.modes.*;
    import org.bouncycastle.crypto.params.*;

    // A simple example that uses the Bouncy Castle
    // lightweight cryptography API to perform DES
    // encryption of arbitrary data.


     public class Encryptor {

            private BufferedBlockCipher cipher;
            private KeyParameter key;


            // Initialize the cryptographic engine.
            // The key array should be at least 8 bytes long.


            public Encryptor( byte[] key ){
            /*
            cipher = new PaddedBlockCipher(
                       new CBCBlockCipher(new DESEngine()));
            */
            cipher = new PaddedBlockCipher(
                        new CBCBlockCipher(new BlowfishEngine()));
            this.key = new KeyParameter( key );
            }        

            // Initialize the cryptographic engine.
            // The string should be at least 8 chars long.

            public Encryptor( String key ){
            this( key.getBytes());
            }
            // Private routine that does the gritty work.

            private byte[] callCipher( byte[] data )
            throws CryptoException {
            int    size = cipher.getOutputSize( data.length );

            byte[] result = new byte[ size ];
            int    olen = cipher.processBytes(data,0,data.length result, 0);
                   olen += cipher.doFinal( result, olen );

            if( olen < size ){
                byte[] tmp = new byte[ olen ];
                System.arraycopy(
                        result, 0, tmp, 0, olen );
                result = tmp;
            }

            return result;
        }
        // Encrypt arbitrary byte array, returning the
        // encrypted data in a different byte array.

        public synchronized byte[] encrypt( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return new byte[0];
            }

            cipher.init( true, key );
            return callCipher( data );
        }
       // Encrypts a string.

        public byte[] encryptString( String data )
        throws CryptoException {
            if( data == null || data.length() == 0 ){
                return new byte[0];
            }

            return encrypt( data.getBytes() );
        }
        // Decrypts arbitrary data.

        public synchronized byte[] decrypt( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return new byte[0];
            }

            cipher.init( false, key );
            return callCipher( data );
        }
        // Decrypts a string that was previously encoded
        // using encryptString.

        public String decryptString( byte[] data )
        throws CryptoException {
            if( data == null || data.length == 0 ){
                return "";
            }

            return new String( decrypt( data ) );
        }
    }
查看更多
放我归山
4楼-- · 2019-01-08 15:07

An easy and fun scrambling algorithm would be the Burrows-Wheeler transform. Not really a secure encryption, but seriously, it's a school work and this is awesome.

查看更多
孤傲高冷的网名
5楼-- · 2019-01-08 15:12
public class CryptoUtils {

    public static void encrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.ENCRYPT_MODE, key, inputFile, outputFile);
    }

    public static void decrypt(String key, File inputFile, File outputFile)
            throws CryptoException {
        doCrypto(Cipher.DECRYPT_MODE, key, inputFile, outputFile);
    }

    private static void doCrypto(int cipherMode, String key, File inputFile,
            File outputFile) throws CryptoException {
        try {
            Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);

            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);

            byte[] outputBytes = cipher.doFinal(inputBytes);

            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);

            inputStream.close();
            outputStream.close();

        } catch (NoSuchPaddingException | NoSuchAlgorithmException
                | InvalidKeyException | BadPaddingException
                | IllegalBlockSizeException | IOException ex) {
            throw new CryptoException("Error encrypting/decrypting file", ex);
        }
    }
}

package net.codejava.crypto;

import java.io.File;

public class CryptoException extends Exception {

    public CryptoException() {
    }

    public CryptoException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public static void main(String[] args) {
        String key = "Mary has one cat1";
        File inputFile = new File("document.txt");
        File encryptedFile = new File("document.encrypted");
        File decryptedFile = new File("document.decrypted");

        try {
            CryptoUtils.encrypt(key, inputFile, encryptedFile);
            CryptoUtils.decrypt(key, encryptedFile, decryptedFile);
        } catch (CryptoException ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
    }
}
查看更多
登录 后发表回答