Simplest way to encrypt a text file in java

前端 未结 11 1502
萌比男神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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题