Software Secret Weapons™
|
MD5 For AJAX by Pavel Simakov on 2007-05-07 16:14:30 under AJAX, view comments |
|||||
|
|
The variety of good quality MD5 implementations exists After some looking around and help from one of my friends, I have collected the code snippets for MD5 signing of text with the key for PHP, Java, JavaScript (and ActionScript). Now I can cryptographically sign some text in the AJAX application using JavaScript (or in the Flash Movie using ActionScript). The signature can then be sent to a server and verified in either PHP or Java. Or in reverse, the server can send a signature that client can verify in the browser. All examples below sign the word "foo" with the key "bar" to produce a signature: 31b6db9e5eb4addb42f1a6ca07367adc. Enjoy!
For PHP
<?php $sign = bin2hex(mhash(MHASH_MD5, "foo", "bar")); echo $sign; ?> If function mhash() is not available in your PHP setting, here is an alternative:
<?php
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// Hacked by Lance Rushing
function hmac ($key, $data){
$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;
return md5($k_opad . pack("H*",md5($k_ipad . $data)));
}
?>
For JavaScript
<script src="md5.js"></script>
<script language="JavaScript">
var sign = hex_hmac_md5("bar", "foo");
alert(sign);
</script>
For Java (1.4.2+)
import java.security.Provider;
import java.security.Security;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class MyMD5 {
public static String string2md5HMA(String keyString, String message) {
Provider sunJce = new com.sun.crypto.provider.SunJCE();
Security.insertProviderAt(sunJce,0);
SecretKey key = new SecretKeySpec(keyString.getBytes(), "HmacMD5");
try {
Mac mac = Mac.getInstance("HmacMD5");
mac.init(key);
return toHEX(mac.doFinal(message.getBytes()));
} catch (Exception e) {
throw new RuntimeException("Failed to create signature", e);
}
}
private static String toHEX(byte[] digest) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; ++i) {
String hx = Integer.toHexString(0xFF & digest[i]);
if (hx.length() == 1) {
hx = "0" + hx;
}
hexString.append(hx);
}
return hexString.toString();
}
public static void main(String [] args){
System.out.println(string2md5HMA("bar", "foo"));
}
}
Comment (1) Leave a comment |
|
||||
|
Copyright © 2004-2012 by Pavel Simakov
any conclusions, recommendations, ideas, thoughts or the source code presented on this site are my own and do not reflect a official opinion of my current or past employers, partners or clients |
Comment by Shanky Baba — May 4, 2009 @ 8:32 pm
Thanks man! This is a great article. Works like charm.