Programmer's Wiki

For more information on the SHA algorithm and pseudocode, visit the Wikipedia article

Code snippets[]

C#[]

The following is an example of an SHA checksum in C# (using the System.Security.Cryptography namespace).

public class SHA1Test
{
  public static byte[] Compute(byte[] input)
  {
    // Initialize the engine
    SHA1 engine = new SHA1CryptoServiceProvider();

    // Compute the hash
    byte[] hash = engine.ComputeHash(input);

    // Return the result
    return hash;
  }
}

MSDN documentation for the SHA1CryptoServiceProvider class

Java[]

The following is an example of an SHA checksum in Java. Java Code Examples

import java.security.MessageDigest;

public static String SHAsum(byte[] convertme) {
   MessageDigest md = MessageDigest.getInstance("SHA-1"); //This could also be SHA1withDSA, no exception handling
   return new String(md.digest(convertme));
}

MessageDigest API from Sun

Java Cryptography Architecture

Perl[]

The following is an example of an SHA checksum in Perl.

# Functional style Perl 5.6.x or earlier
 use Digest::file qw(digest_file_base64);

 my $full_filename='c:/yourpath/yourfile.ext';  # on Linux
 # my $full_filename='c:\\yourpath\\yourfile.ext';  # on Windows
 my $digest='';
 $digest = digest_file_base64( $file, 'SHA1' ) unless -d $file;    # skip directories!
__END__
# Functional style Perl 5.8.x or later
 use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);

 $digest = sha1($data);
 $digest = sha1_hex($data);
 $digest = sha1_base64($data);
 $digest = sha1_transform($data);

PHP[]

The following is an example of an SHA checksum in PHP.

$digest = sha1($data);
$digest = hash('sha1',$data);

Note that hash() is available in PHP 5 and above.

Python[]

The following is an example of an SHA checksum in Python.

import hashlib

converted = hashlib.sha1("My text").hexdigest()

Python hashlib reference

Tcl[]

The following is an example of a SHA1 checksum using Tcl.

package require sha1
set digest [sha1::sha1 -hex "My text"]

Tcllib sha1 manual page

See also[]

MD5 checksum