Simplest way to encrypt a text file in java

前端 未结 11 1499
萌比男神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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-30 01:52

    You could use a simple ceasar cipher (http://en.wikipedia.org/wiki/Caesar_cipher)

    public class Cipher {
    public static void main(String[] args) {
    
        String str = "The quick brown fox Jumped over the lazy Dog";
    
        System.out.println( Cipher.encode( str, 12 ));
        System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));
    }
    
    public static String decode(String enc, int offset) {
        return encode(enc, 26-offset);
    }
    
    public static String encode(String enc, int offset) {
        offset = offset % 26 + 26;
        StringBuilder encoded = new StringBuilder();
        for (char i : enc.toCharArray()) {
            if (Character.isLetter(i)) {
                if (Character.isUpperCase(i)) {
                    encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                } else {
                    encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                }
            } else {
                encoded.append(i);
            }
        }
        return encoded.toString();
    }
    }
    

    Found at http://rosettacode.org/wiki/Caesar_cipher#Java

    Note that Java has native solutions for encryption and when it comes to passwords, it is much better to just hash them and compare hashes as there usually is no need to decrypt them.

    0 讨论(0)
  • 2020-11-30 01:52

    My suggestion: don't use encryption at all. Here's something better:(I hope)

    Scanner sc=new Scanner(System.in);
    String name=sc.next();
    //for inputting user name
    File f= new File("d://"+name+".txt");
    if(f.exists())
    {
    if(f.lastModified()!=0)
    { 
    System.out.println("Account data tampered...cannot be accessed"); 
    }
    else{
    String data="";
    System.out.println(data); //data should contain 
    //data from file read using BufferedReader
    f.setLastModified(0);
    }
    }
    else
    {
    f.createNewFile();//Write whatever you want to to the file 
    f.setLastModified(0);
    }
    

    So, you can effectively know whether the user has tampered with the text file with the details and display an error message if the tampered account is used. However, This does not prevent the user from changing the file, it will just prevent a tampered account from being used....I think your computer teacher might like this. You could also do: f.setReadOnly(); and when you write to the file, f.setWritable(true,true), then after closing the output stream, f.setReadOnly(); again... But the file can still be replaced, therefore the 1st and is more Effective. Thanks

    0 讨论(0)
  • 2020-11-30 01:55

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

    • cite your reference as theoric support to your cryptographic solution. I sugget you this OWSAP - Password Storage Cheat Sheet
    • explain where your code meets specification. For a good tutorial with sample code I suggest you this secure password hash

    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!

    0 讨论(0)
  • 2020-11-30 01:56

    There are too many ways to encrypted simple string in Java. If it is a school project , I really don't think you can get a higher band by simply using some third-part libs to finish the encrypted work.

    If you have some time, you could try to understand how Base64 works, then try to create some encrypted algorithm by yourself.

    How ever, if you insist to use some API in Java , I have to say that DES is really old way to encrypted text , 3DEs(DESede) or AES will be better and safer , both of them have already been supported since Java6.

    If you have to import the BouncyCastle lib , I prefer IDEA, it's one of the safest algorithm, may have you achieve a good score.

    I won't give you any demo code, but you can easily find some by google all the algorithm I have mentioned.

    0 讨论(0)
  • 2020-11-30 01:59

    Try this,... Its pretty simple

    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    
    public class HelloWorld{
        public static void main(String[] args) {
    
            try{
                KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
                SecretKey myDesKey = keygenerator.generateKey();
    
                Cipher desCipher;
                desCipher = Cipher.getInstance("DES");
    
    
                byte[] text = "No body can see me.".getBytes("UTF8");
    
    
                desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
                byte[] textEncrypted = desCipher.doFinal(text);
    
                String s = new String(textEncrypted);
                System.out.println(s);
    
                desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
                byte[] textDecrypted = desCipher.doFinal(textEncrypted);
    
                s = new String(textDecrypted);
                System.out.println(s);
            }catch(Exception e)
            {
                System.out.println("Exception");
            }
        }
    }
    

    So basically before writing to file you will encrypt and after reading you will need to decrypt it.

    0 讨论(0)
提交回复
热议问题