Digest::MD5

Digest::MD5是perl的一个模块,其目的是将所有字符累加,存储为二进制编码,16进制编码,base64编码。
j具体参考:http://perldoc.perl.org/Digest/MD5.html
md5($data,...)

This function will concatenate all arguments, calculate the MD5 digest of this "message", and return it in binary form. The returned string will be 16 bytes long.

The result of md5("a", "b", "c") will be exactly the same as the result of md5("abc").

md5_hex($data,...)

Same as md5(), but will return the digest in hexadecimal form. The length of the returned string will be 32 and it will only contain characters from this set: '0'..'9' and 'a'..'f'.

md5_base64($data,...)

Same as md5(), but will return the digest as a base64 encoded string. The length of the returned string will be 22 and it will only contain characters from this set: 'A'..'Z', 'a'..'z', '0'..'9', '+' and '/'.

Note that the base64 encoded string returned is not padded to be a multiple of 4 bytes long. If you want interoperability with other base64 encoded md5 digests you might want to append the redundant string "==" to the result.


#!/usr/bin/perl

use strict;
use Digest::MD5;

my $file_1 = shift || '/etc/passwd';    
open( FILE, $file_1 ) or die "Can't open '$file_1': $!";    #打开目录为/etc/passwd的文件;
binmode(FILE);     #FILE被读出和写入二进制的操作系统

my $md5 = Digest::MD5->new;
while () {
    $md5->add($_);
}
close(FILE);
print $md5->hexdigest, " $file_1\n";

###另外一种实现方法

my $file_2 = shift || '/etc/passwd';
open( FH, $file_2 ) or die "Can't open '$file_2': $!";
binmode(FH);

print Digest::MD5->new->addfile(*FH)->hexdigest, " $file_2\n";

输出如下:
[root@mail test]# ./md5.pl
70cd6c28d0037ad92301e07d47921c75 /etc/passwd
70cd6c28d0037ad92301e07d47921c75 /etc/passwd

如果是在shell环境下,这样输入:

[root@mail test]# cat /etc/passwd | md5sum
70cd6c28d0037ad92301e07d47921c75  -

结果完全一样,呵呵,当然是第2种方法最方便快捷了!

相关推荐

你的评论

就没有什么想说的吗?

最新博客

关于我们 移动版

©2017传客网    琼ICP备15003173号-2    

本站部分文章来源于互联网,版权归属于原作者。
本站所有转载文章言论不代表本站观点,如是侵犯了原作者的权利请发邮件联系站长(weishubao@126.com),我们收到后立即删除。
站内所有资源仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您自己承担!

X