HMAC SHA-256 sample. I will write more if I have time.
Secret key secret key
ยท Target This is a pen.
Signed with HMAC SHA-256.
The output will be b4197908ed255480db6bbedb27426c89520bcd3b79c81006f70a94f415b43a43
.
First Java.
package example.misc;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HmacDemo {
private static final String SECRET = "secret key";
private static final String TEXT = "This is a pen.";
public static void main(String[] args) throws Exception {
String algo = "HMacSHA256";
final SecretKeySpec keySpec = new SecretKeySpec(SECRET.getBytes(),
algo);
final Mac mac = Mac.getInstance(algo);
mac.init(keySpec);
final byte[] signBytes = mac.doFinal(TEXT.getBytes());
for (byte signByte : signBytes) {
System.out.printf("%02x", signByte & 0xff);
}
System.out.print("\n");
}
}
The algorithm specification is redundant, but is there only such a way of writing? It would be nice if the hexadecimal output of the byte string could be made a little cleaner. The Base64 encoded library accepts byte strings as they are. In this case, it may be good.
Next is Python
#!/usr/bin/python3
import hashlib
import hmac
SECRET = "secret key"
TEXT = "This is a pen."
print(hmac.new(bytes(SECRET, 'ascii'), bytes(TEXT, 'ascii'), hashlib.sha256).hexdigest())
Next Ruby.
#!/usr/bin/ruby
require 'openssl'
SECRET = "secret key"
TEXT = "This is a pen."
puts OpenSSL::HMAC.digest(OpenSSL::Digest::Digest.new('sha256'),
SECRET, TEXT).unpack("H*")
Recommended Posts