How do I check if a string is a valid md5 or sha1 checksum string
Question
I don't want to calculate a file's checksum, just to know if a given string is a valid checksum
Solution
SHA1 verifier:
public boolean isValidSHA1(String s) {
return s.matches("^[a-fA-F0-9]{40}$");
}
MD5 verifier:
public boolean isValidMD5(String s) {
return s.matches("^[a-fA-F0-9]{32}$");
}
OTHER TIPS
Any 160-bit sequence is a possible SHA1 hash. Any 128-bit sequence is a possible MD5 hash.
If you're looking at the hex string representations of them, then a sha1 will look like 40 hexadecimal digits, and an md5 will look like 32 hexadecimal digits.
MD5 verifier:
public boolean isValidMD5(String s) {
return s.matches("[a-fA-F0-9]{32}");}
And remove "-" of the string value.
RegExp SHA-1
public static final String SHA_1 = "^([0-9A-Fa-f]{2}[:]){19}([0-9A-Fa-f]{2})$";
public boolean isValidSHA1(String s) {
return s.matches(SHA_1);
}
boolean isValidSHA1 = isValidSHA1("12:45:54:3A:99:24:52:EA...");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow