Skip to content

Instantly share code, notes, and snippets.

@daohoangson
Created April 20, 2022 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daohoangson/844daca56d1687e8b95d29f77f3c4e25 to your computer and use it in GitHub Desktop.
Save daohoangson/844daca56d1687e8b95d29f77f3c4e25 to your computer and use it in GitHub Desktop.
HMAC / SHA256 in different languagues
const crypto = require('crypto');
function encode(data, key) {
return crypto
.createHmac('sha256', key)
.update(data)
.digest('base64');
}
console.log(encode('{"foo":"bar"}', 's3cret'));
<?php
function encode($data, $key) {
$hashed = hash_hmac('sha256', $data, $key, true);
$encoded = base64_encode($hashed);
return $encoded;
}
print(encode('{"foo":"bar"}', 's3cret'));
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
class Main {
public static String encode(String data, String key) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
Mac sha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec spec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
sha256.init(spec);
byte[] hashed = sha256.doFinal(data.getBytes("UTF-8"));
String encoded = Base64.getEncoder().encodeToString(hashed);
return encoded;
}
public static void main(String args[]) {
try {
System.out.println(encode("{\"foo\":\"bar\"}", "s3cret"));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
using System;
using System.Security.Cryptography;
class Program {
static String encode(String data, String key) {
var utf8 = System.Text.Encoding.UTF8;
var sha256 = new HMACSHA256(utf8.GetBytes(key));
var hashed = sha256.ComputeHash(utf8.GetBytes(data));
var encoded = System.Convert.ToBase64String(hashed);
return encoded;
}
static void Main(string[] args) {
Console.WriteLine(encode("{\"foo\":\"bar\"}", "s3cret"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment