Skip to content

Instantly share code, notes, and snippets.

@whiler
Last active June 5, 2023 09:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
@shagle
Copy link

shagle commented May 5, 2022

当message含有换行符“\n”时,得到的结果不符要求,与python获得的结果不一致。

@Mindzy
Copy link

Mindzy commented May 22, 2022

当message含有换行符“\n”时,得到的结果不符要求,与python获得的结果不一致。

可以用tr -d '\n'删除

@whiler
Copy link
Author

whiler commented May 24, 2022

当message含有换行符“\n”时,得到的结果不符要求,与python获得的结果不一致。

多谢反馈,出现这个问题的原因是 echo 命令没有激活转义。加上 -e 参数激活转义后,与 python 的结果一致。

@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