一、簡介
md5sum計算檢驗MD5效驗碼。MD5算法常常被用來驗證網(wǎng)絡文件傳輸?shù)耐暾?,防止文件被人篡改。MD5全稱是報文摘要算法(Message-Digest Algorithm 5),此算法對任意長度的信息逐位進行計算,產(chǎn)生一個二進制長度為128位(十六進制長度就是32位)的“指紋”(或稱“報文摘要”),不同的文件產(chǎn)生相同的報文摘要的可能性非常小。
一般來說,安裝了Linux后,就會有md5sum這個工具,直接在命令行終端直接運行。其他兩個工具sha256sum和sha512sum的工作方式與md5sum相同。
二、基本命令
$ md5sum --help
Usage: md5sum [OPTION]... [FILE]...
Print or check MD5 (128-bit) checksums.
With no FILE, or when FILE is -, read standard input.
-t, --text read in text mode (default)
-b, --binary read in binary mode
-c, --check read MD5 sums from the FILEs and check them
--tag create a BSD-style checksum
Note: There is no difference between binary and text mode option on GNU system.
The following four options are useful only when verifying checksums:
--quiet don't print OK for each successfully verified file
--status don't output anything, status code shows success
--strict exit non-zero for improperly formatted checksum lines
-w, --warn warn about improperly formatted checksum lines
--help display this help and exit
--version output version information and exit
The sums are computed as described in RFC 1321. When checking, the input
should be a former output of this program. The default mode is to print
a line with checksum, a character indicating input mode ('*' for binary,
space for text), and name for each FILE.
md5sum filename > filename.md5
也可以把多個文件的報文摘要輸出到一個md5文件中,這要使用通配符 *,比如某目錄下有幾個iso文件,要把這幾個iso文件的摘要輸出到iso.md5文件中,命令如下:
md5sum *.iso > iso.md5
特殊說明:
1)md5sum 是校驗文件內容,與文件名是否相同無關
2)md5sum值逐位校驗,所以文件越大,校驗時間越長。
三、常見功能
1. 驗證文件是否被篡改
把下載的文件file和該文件的file.md5報文摘要文件放在同一個目錄下,然后用如下命令進行驗證:
md5sum -c file.md5
然后如果驗證成功,則會輸出:OK
2. 驗證多個文件
md5sum命令可以一次驗證多個文件。如果將散列寫入文件,則可以使用該文件檢查是否有任何文件已更改。 在這里,我們先將文件的散列寫入文件散列,然后使用它來驗證沒有任何文件已經(jīng)改變。
$ md5sum file1.txt file2.txt file3.txt > hashes
$ md5sum --check hashes
file1.txt: OK
file2.txt: OK
file3.txt: OK
現(xiàn)在我們將更改file3.txt,在文件末尾添加一個感嘆號,然后重新運行該命令。
echo "!" >> file3.txt
$ md5sum --check hashes
file1.txt: OK
file2.txt: OK
file3.txt: FAILED
md5sum: WARNING: 1 computed checksum did NOT match
可以看到file3.txt已經(jīng)改變了。
3. 只顯示修改過的文件
如果有許多文件需要檢查,可能只想顯示已更改的文件。 使用--quiet選項,md5sum將只列出已經(jīng)改變的文件。
$ md5sum --quiet --check hashes
file3.txt: FAILED
md5sum: WARNING: 1 computed checksum did NOT match
4. 遞歸生成各文件的的MD5值
find ./test_rc1 -type f -print0| xargs -0 md5sum >> rc1_md5.txt
find ./test_rc2 -type f -print0| xargs -0 md5sum >> rc2_md5.txt
5. 比較兩文件的MD5值
diff -c rc1_md5.txt rc2_md5.txt
Ref: