I have written this code to read from the file first after hashing the content from the file. It will write the original content plus hash values. But when I try to run the program the program will keep on writing and won't stop. what is the problem with my code?
package Encrypt;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\Tan\\Desktop\\Test.txt");
Scanner scan = new Scanner(file);
FileWriter writer = new FileWriter("C:\\Users\\Tan\\Desktop\\Test.txt", true);
while(scan.hasNextLine()) {
String password = scan.nextLine();
MessageDigest md;
try {
// Select the message digest for the hash computation -> SHA-256
md = MessageDigest.getInstance("SHA-256");
// Generate the random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
// Passing the salt to the digest for the computation
//md.update(salt);
// Generate the salted hash
byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hashedPassword)
sb.append(String.format("%02x", b));
//Print output
System.out.println(password + " " + sb.toString());
//write output to text file
writer.write(password + " " + sb + System.getProperty("line.separator"));
writer.flush();
}
catch (NoSuchAlgorithmException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
scan.close();
writer.close();
}
}
You specified true
as the append
argument of FileWriter
s constructor. So you are probalby reading what you previously written into the file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.