Simplest way to encrypt a text file in java

前端 未结 11 1518
萌比男神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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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

提交回复
热议问题