swapnil dahule
swapnil dahule

Reputation: 31

Checksum for keeping the integrity of the timestamp

I have timestamp which is basically "ddMMYYHHMMss". what i want to do is everytime i run the program the seconds value change but my checksum remains the same. can anyone help me with this. i want the checksum should change everytime the seconds(time) changes.

public class Checksum {
public static void main(String[] args) throws IOException {
    File f = new File("D:/test.txt");
    PrintWriter pw = new PrintWriter(f);
    if(!f.exists()){
        f.createNewFile();
    }
    Date d = new Date();
    SimpleDateFormat sd = new SimpleDateFormat("ddMMYYHHmmss");
    String formatteddate = sd.format(d);
    System.out.println(formatteddate);
    pw.println(formatteddate);
    pw.close();

    BufferedReader br = new BufferedReader(new FileReader(f));
    String line = null;

    while((line = br.readLine()) != null){
        break;
    }
    br.close();

    System.out.println("MD5    : " + toHex(Hash.MD5.checksum(line)));
    System.out.println("SHA1   : " + toHex(Hash.SHA1.checksum(line)));
    System.out.println("SHA256 : " + toHex(Hash.SHA256.checksum(line)));
    System.out.println("SHA512 : " + toHex(Hash.SHA512.checksum(line)));
}
 private static String toHex(byte[] bytes) {
        return DatatypeConverter.printHexBinary(bytes);
    }
}

class CheckSumGenerator {
public enum Hash {

    MD5("MD5"), SHA1("SHA1"), SHA256("SHA-256"), SHA512("SHA-512");

    private String name;

    Hash(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public byte[] checksum(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance(getName());
            byte[] block = new byte[4096];
            int length;
            if (input.length()> 0) {
                digest.update(block, 0, input.length());
            }
            return digest.digest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

}

Upvotes: 2

Views: 1486

Answers (1)

stephendnicholas
stephendnicholas

Reputation: 1830

You never actually pass your input into the digest.update(...) call. You always pass the same empty byte array: block = new byte[4096]; Therefore it will always return the same

Upvotes: 2

Related Questions