Tuesday, February 08, 2011

Public/Private Key Encryption with Java and PHP

Lately, I was struggling with the differences between PHP and Java HMAC encryption methods. Although encryption is rarely used in my most day to day programming tasks, it can probably be useful for people who may need it in the future.

In specific HMAC-SHA256 is used "for calculating a message authentication code (MAC) involving a cryptographic hash function in combination with a secret key". An interesting scenario is that a service that is hosted in a PHP Web application Server interacts with a Java client application client that consumes this service (for example Android mobile application). Since the client knows its private key it can encrypt an agreed message so the server then can verify with the given encrypted signature and authenticate the client.

Enough with talking, let's see how it is done in Java vs. PHP with the following code snippets:

* Encryption of a given text using the provided secretKey
* @param text
* @param secretKey
* @return the encoded string
* @throws SignatureException
public static String hashMac(String text, String secretKey)
throws SignatureException {

try {
Key sk = new SecretKeySpec(secretKey.getBytes(), HASH_ALGORITHM);
Mac mac = Mac.getInstance(sk.getAlgorithm());
final byte[] hmac = mac.doFinal(text.getBytes());
return toHexString(hmac);
} catch (NoSuchAlgorithmException e1) {
// throw an exception or pick a different encryption method
throw new SignatureException(
"error building signature, no such algorithm in device "
} catch (InvalidKeyException e) {
throw new SignatureException(
"error building signature, invalid key " + HASH_ALGORITHM);

where HASH_ALGORITHM is defined as

private static final String HASH_ALGORITHM = "HmacSHA256";

Where in PHP, it's even simpler:

echo hash_hmac('sha256', $message, $secretKey, false);