java 如何检查字符串是否是有效的 md5 或 sha1 校验和字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1896715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I check if a string is a valid md5 or sha1 checksum string
提问by yossis
I don't want to calculate a file's checksum, just to know if a given string is a valid checksum
我不想计算文件的校验和,只是想知道给定的字符串是否是有效的校验和
回答by dfa
SHA1 verifier:
SHA1 验证器:
public boolean isValidSHA1(String s) {
return s.matches("^[a-fA-F0-9]{40}$");
}
MD5 verifier:
MD5 验证器:
public boolean isValidMD5(String s) {
return s.matches("^[a-fA-F0-9]{32}$");
}
回答by Jonathan Feinberg
Any 160-bit sequence is a possible SHA1 hash. Any 128-bit sequence is a possible MD5 hash.
任何 160 位序列都是可能的 SHA1 哈希。任何 128 位序列都是可能的 MD5 哈希。
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.
如果您查看它们的十六进制字符串表示,那么 sha1 将看起来像 40 个十六进制数字,而 md5 看起来像 32 个十六进制数字。
回答by Maarten Bodewes
There is no such thing as an MD5 or SHA-1 string, at least not one that is standardized. All you can test for is the size of the byte array: 16 for MD5 (a hash with an output size of 128 bits) or 20 bytes for SHA-1 (a hash with an output size of 160 bits) encoded using hexadecimal encoding or base 64 encoding.
没有 MD5 或 SHA-1 字符串之类的东西,至少没有标准化的字符串。您可以测试的只是字节数组的大小:MD5 为 16(输出大小为 128 位的散列)或 SHA-1(输出大小为 160 位的散列)为 20 字节,使用十六进制编码或base 64 编码。
If you use md5sumthen generally the checksum is shown as hexadecimal encoding, using onlylowercase characters (followed by the file name or -for standard input). Hexadecimals are generally preferred, but hashes may also contain separator character or use a different encoding such as base 64 or base 64 URL (etc. etc.).
如果您使用,md5sum则校验和通常显示为十六进制编码,仅使用小写字符(后跟文件名或-标准输入)。通常首选十六进制,但散列也可能包含分隔符或使用不同的编码,例如 base 64 或 base 64 URL(等等)。
The byte size you are testing for might however belong to an entirely different hash such as RIPEMDthat may also have the same output size. Or it may be another value with the same amount of bytes.
但是,您正在测试的字节大小可能属于完全不同的哈希,例如RIPEMD,它们也可能具有相同的输出大小。或者它可能是具有相同字节数的另一个值。
回答by raphaRezzi
MD5 verifier:
MD5 验证器:
public boolean isValidMD5(String s) {
return s.matches("[a-fA-F0-9]{32}");}
And remove "-" of the string value.
并删除字符串值的“-”。
回答by Vahe Gharibyan
RegExp SHA-1
正则表达式 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...");

