简体   繁体   English

如何检查字符串是否是有效的 md5 或 sha1 校验和字符串

[英]How do I check if a string is a valid md5 or sha1 checksum string

我不想计算文件的校验和,只是想知道给定的字符串是否是有效的校验和

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}$");
}

Any 160-bit sequence is a possible SHA1 hash.任何 160 位序列都是可能的 SHA1 哈希。 Any 128-bit sequence is a possible MD5 hash.任何 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 个十六进制数字。

There is no such thing as an MD5 or SHA-1 string, at least not one that is standardized.没有 MD5 或 SHA-1 字符串之类的东西,至少没有标准化的字符串。 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(输出大小为 128 位的散列)为 16 字节或 SHA-1(输出大小为 160 位的散列)为 20 个字节,或base 64 编码。

If you use md5sum then generally the checksum is shown as hexadecimal encoding, using only lowercase characters (followed by the file name or - for standard input).如果您使用md5sum则校验和通常显示为十六进制编码,使用小写字符(后跟文件名或-用于标准输入)。 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.).通常首选十六进制,但散列也可能包含分隔符或使用不同的编码,例如 base 64 或 base 64 URL(等等)。

The byte size you are testing for might however belong to an entirely different hash such as RIPEMD that may also have the same output size.但是,您正在测试的字节大小可能属于完全不同的哈希,例如RIPEMD ,它们也可能具有相同的输出大小。 Or it may be another value with the same amount of bytes.或者它可能是具有相同字节数的另一个值。

MD5 verifier: MD5 验证器:

public boolean isValidMD5(String s) {
return s.matches("[a-fA-F0-9]{32}");}

And remove "-" of the string value.并删除字符串值的“-”。

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...");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM