Reputation: 51
I have seen a lot of posts about how to create a HMAC in PHP, but the used secret was always a simple string (eg. "secret"). What I need to do is create a HMAC with the secret being a private key, loaded for example from a file containing private key in PEM format. I have been unable to find any information on whether this is possible in PHP (using hash_hmac) or not.
A HmacSHA256 signature using a private key is created in Java and I would like to recreate this signature in PHP (from my understanding using hash_hmac with sha256 hashing algorithm) with the same private key loaded from a file.
To clarify: the private key in this scenario is used as a shared secret key, meaning that two parties have the key. The message verification process consists of sending a HMAC with the message, calculated with the private key, while the recipient calculates HMAC with an identical private key and verifies it against the sent signature.
Java:
byte[] data = getDataForSignature();
PrivateKey key = getPrivateKey(); // loaded from a file
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(key);
byte[] hmac = mac.doFinal(data);
// compare hmac with received signature bytes
PHP:
$key = openssl_pkey_get_private("private.key");
$sig = hash_hmac("sha256", $data, $key??, true);
Sample private key
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQCSWro05ZKVGxMTCqAyNZRAXp8Gd7wf6vywXRsFckm9MHOAWZL0
SvFAhM6tlCthuPkQb0c+Hx9PWH1+4sW2u3O+VDvjQEB0ZILd79LraBEshK/36Oux
yyw2K+ghk9Yh00nJOzkkonmdZmVxr0AAzw5el2h9yDjlUa1E8BH/1LzBBwIDAQAB
AoGANtwXbHiZh5bMgZi8D9YRqkdNqOj89aHp8loUJOiAR5B/2x64fSYSZLLjniEq
WckyYzyzIdActmtfL07l+ecuLRipsHoHuzjPiiRRnzJQbgBstnB8rHkuN275YSbC
3gE7nyyX0JPEviwqHv++Uig0RCD1ZbrG0SBMKBlGVrFMddECQQDmVguRhRScTJHH
RaXY/zjZtHp0L1dtzzSLM75+ji2UoRy1yK9z+rnE1PM5QC8PQixbwocGwpRIwGQn
hIg1YAM9AkEAoqk+VNbJ9ykoP9r+8o1PrPR1Ff+EIhpTthRyFngHNbNnOFB0D314
+V4wyO+a/gbiIAmvTuOXV/GwOlgnfVDJkwJBAJNHd5QvxPL/3sLNXPN4ljBWP2pl
DwFO2Wkcx/SCEtETh5kQ3mdJbVlXVMJJsQ2PoW923gHLjydJpYDDNJj0cH0CQQCW
8txHOvQ+C9GwQHirenvgExO9EFv8kdXxeNPPCiAWs6AsYGz0Gwpyz/gR4FlDN/wM
ozAu04IVONLDsh8jah9FAkEAsSUvlo7Nh1ITd75kUsStv7Tjxma3SuKViewWCprD
olDNtncfcZC5SrilHAJEabVxGy1fJL3hYvTYfqNkeB1TcA==
-----END RSA PRIVATE KEY-----
Upvotes: 5
Views: 3272
Reputation: 93948
Usually a private key is used to perform signature generation which is the asymmetric equivalent to creating a MAC with a symmetric secret key.
Note that a HMAC key can consist of any binary string, so in principle it would be possible to use HMAC with a binary encoded private key. That said, it doesn't make sense to use a asymmetric private key for HMAC. Only the person holding the private key would be able to verify the resulting authentication tag. In comparison, digital signatures can be verified using the public key of the key pair.
Now if you have a secret key that was used within Java then you need to create the same (binary) key
parameter for the PHP hash_hmac
function.
Upvotes: 2