Simplest way to encrypt a text file in java

前端 未结 11 1501
萌比男神i
萌比男神i 2020-11-30 01:18

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 wri

11条回答
  •  渐次进展
    2020-11-30 01:51

    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();
            }
        }
    }
    

提交回复
热议问题