Message Digest - SHA1 Algorithm
Part:
1
2
3
4
(Continued from previous part...)
Here is a sample Java program to show you how to use the MessageDigest class to perform some tests
on SHA1 algorithms.
/**
* JceSha1Test.java
* Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
*/
import java.security.*;
class JceSha1Test {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = "+md.getAlgorithm());
System.out.println(" Provider = "+md.getProvider());
System.out.println(" toString = "+md.toString());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") =");
System.out.println(" "+bytesToHex(output));
} catch (Exception e) {
System.out.println("Exception: "+e);
}
}
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
}
}
If you run this sample program with JDK 1.5, you should get the following output:
Message digest object info:
Algorithm = SHA1
Provider = SUN version 1.5
toString = SHA1 Message Digest from SUN, <initialized>
SHA1("") =
DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
SHA1("abc") =
A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz") =
32D10C7B8CF96570CA04CE37F2A19D84240D3A89
SHA1 Implementation in PHP
If you are interested in using SHA1 in PHP, you can use the built-in function sha1().
Here is a sample program showing you how to use sha1() function:
<?php # PhpSha1Test.php
# Copyright (c) 2006 by Dr. Herong Yang, http://www.herongyang.com/
#
$input = "";
$output = sha1($input);
print("\n");
print("SHA1(\"".$input."\") =\n");
print(" $output\n");
$input = "abc";
$output = sha1($input);
print("\n");
print("SHA1(\"".$input."\") =\n");
print(" $output\n");
$input = "abcdefghijklmnopqrstuvwxyz";
$output = sha1($input);
print("\n");
print("SHA1(\"".$input."\") =\n");
print(" $output\n");
?>
(Continued on next part...)
Part:
1
2
3
4
|