LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Perl SHA256SUM Clarification (https://www.linuxquestions.org/questions/programming-9/perl-sha256sum-clarification-865025/)

Sky.Crawler 02-25-2011 12:46 PM

Perl SHA256SUM Clarification
 
I am writing a perl script to take the SHA256SUM of every image file in a directory. The problem is that the SHA256SUM created by perl is different than the one created by the straight sha256sum utility from the command line.

The perl script returns hashes much quicker than the command line, leading me to believe the image files are not actually being used, but some other value (like their names for instance).

I am using "strict" and "warnings", and no errors are being returned.

PHP Code:

use Digest::SHA;

# Code Omitted

opendir(my $dh$STARTING_DIRECTORY) or die "Cannot open directory: $!";
while (
readdir $dh)
{
    
# Strip out the "." and the ".."
    
unless ($_ eq '.' or $_ eq '..')
    {
        
# Wrap up the filename for convenience
        # It's equal to the absolute path to the file
        
my $absolute "$STARTING_DIRECTORY$_";
        
        
# Calculate SHA256SUM
        
my $digest Digest::SHA->new(256);
        
$digest->add($absolute);
        
my $hash $digest->hexdigest();
        print 
$hash$_\n";
    }

# Code Omitted 

Because these are image files, I do not need them to be read line-by-line, only in one piece, like the command line utility does it. How can I accomplish this?

bigearsbilly 02-26-2011 02:55 AM

if you want to slurp a whole file as one string:

Code:


local $/ = undef;

my $slurp = <>;

print "[$slurp]";

now your hash should work

http://perldoc.perl.org/perlvar.html

or better use Digest::File (I ain't tried it)

http://perldoc.perl.org/Digest/file.html


also, you can shortcut and use a glob pattern rather than readdir

@list = <*.img *.jpg>

it's easier to use find2perl to traverse directories.
perl programming is about laziness!

Sky.Crawler 02-28-2011 08:33 PM

It ended up being a simple fix.

All that had to be done was open the file and switch to a binary reading mode.

PHP Code:

open(FILE"$STARTING_DIRECTORY$_") or die "ERROR. $_ could not be opened: $!";
        
# This is critical to prevent ulcers and create correct SHA256 checksums
binmode(FILE);

# Compute the SHA256 of the file
my $digest Digest::SHA->new(256);
$digest->addfile(*FILE);
my $hash $digest->hexdigest(); 



All times are GMT -5. The time now is 02:45 PM.