[PYTHON] HMAC in various languages

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

HMAC in various languages
[AOJ] Descending sort in various languages
Write classes (or class-like) in various programming languages
Numerical representation of days of the week in various languages
Representing Fibonacci sequences using lambda expressions in various languages
10 Most Popular Programming Languages in 2020
Compete for file IO in various languages and compare speeds
Hello World in various languages [Python / PHP / Java / Perl / Ruby]
I implemented N-Queen in various languages and measured the speed
Let's do "Hello World" in 40 languages! !!
Various Anaconda settings in Windows 10 environment
Summary of various operations in Tensorflow
I made a prime number table output program in various languages
Parallelism with Collections in Popular Languages
Summary of various for statements in Python
Basic writing of various programming languages (self-memo)
I wrote unit tests for various languages
RICOH THETA S API in several languages.
Various comments to write in the program