Skip to content

Instantly share code, notes, and snippets.

@whiler
Last active June 5, 2023 09:46
Show Gist options
  • Save whiler/2f6679123540d03478fb1a96bce5a6fe to your computer and use it in GitHub Desktop.
Save whiler/2f6679123540d03478fb1a96bce5a6fe to your computer and use it in GitHub Desktop.
hmac sha256 encode with url safe base64 in bash shell
$ echo -en "message" | openssl dgst -sha256 -hmac "key" -binary | base64 | sed -e 's/+/-/g' -e 's/\//_/g' | tr -d =
bp7ym3X__Ft6uuUn1Y_a2y_kLnIZARl2kXNDBl9Y7Uo
#!/bin/bash
msg="1\n2"
hmacsha256sh() {
echo -n "${1}" | openssl dgst -sha256 -hmac "key" -binary | base64 | sed -e 's/+/-/g' -e 's/\//_/g' | tr -d =
}
hmacsha256she() {
echo -en "${1}" | openssl dgst -sha256 -hmac "key" -binary | base64 | sed -e 's/+/-/g' -e 's/\//_/g' | tr -d =
}
hmacsha256py() {
local msg=$1
python3 -c "import base64,hashlib,hmac; print(base64.urlsafe_b64encode(hmac.new('key'.encode(), msg='${msg}'.encode(), digestmod=hashlib.sha256).digest()).decode().rstrip('='))"
}
if [[ "$(hmacsha256sh "${msg}")" == "$(hmacsha256py "${msg}")" ]]; then
echo "hmacsha256sh passed"
else
echo "hmacsha256sh failed"
fi
if [[ "$(hmacsha256she "${msg}")" == "$(hmacsha256py "${msg}")" ]]; then
echo "hmacsha256she passed"
else
echo "hmacsha256she failed"
fi
@flydo
Copy link

flydo commented Aug 2, 2022

key 内有 \n 如何处理?飞书群通知的结合比较奇耙。是 message 为空,key 是由 ${timestamp}\n${key} 组合的。

@whiler
Copy link
Author

whiler commented Sep 15, 2022

key 内有 \n 如何处理?飞书群通知的结合比较奇耙。是 message 为空,key 是由 ${timestamp}\n${key} 组合的。

@jetsung
可以先将 key 写入文件 key.dat ,再用

echo -en "message" | openssl dgst -sha256 -hmac "$(cat key.dat)" -binary | base64 | sed -e 's/+/-/g' -e 's/\//_/g' | tr -d =


例如:
hexdump key.dat

0000000 6b 0a 65 79
0000004

结果为 jbb8WsWeeLFGhSJZ73YxcNAagiXHuQDB-WrLRb64BX0 ,和预期一致。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment