使用椭圆曲线secp256k1在命令行中对十六进制字符串进行数字签名 [英] Digitally sign a hex string in command line using elliptic curve secp256k1
问题描述
我正在尝试找到一种最简单的方法来使用也由十六进制值字符串表示的私钥对十六进制值字符串进行数字签名.我可以使用命令行或脚本,但最好使用 openssl
cli.
I'm trying to figure out the most simple way to digitally sign a string of hex values using a private key also represented by a string of hex values. I'm open to command line, or a script, but preferably using openssl
cli.
示例:
- 要签名的字符串:
1333183ddf384da83ed49296136c70d206ad2b19331bf25d390e69b222165e37
- 私钥:
a675c86089e0622c112379906f5cf19ee336575af1bfa1de558051312db9afdc
希望有一个类似的命令:
Hoping there is a command like:
$ openssl sign -msg=1333183ddf384da83ed49296136c70d206ad2b19331bf25d390e69b222165e37 -privkey=a675c86089e0622c112379906f5cf19ee336575af1bfa1de558051312db9afdc
推荐答案
这并非易事,因为您必须以 openssl
支持的格式(不支持原始十六进制字符串)获取私钥..我选择使用.pem格式,因为在线上有示例(请参见底部).
This was not trivial because you have to get private key in a format that openssl
supports (doesn't support raw hex strings). I opted to use .pem format because there were examples online (see bottom).
我最终用bash编写了一个包含键和十六进制字符串的命令行脚本: $ ec_sign_hex< input-hex>< priv-key-hex>
I ended up writing a command line script in bash that takes a key and a hex string:
$ ec_sign_hex <input-hex> <priv-key-hex>
#!/bin/bash
## Command Line parsing
#######################
if [[ $# -lt 2 ]]; then
echo "Usage: $ ec_sign_hex <input-hex> <priv-key-hex>"
exit 1
fi
inputHex=$1
privKeyHex=$2
## Create .pem and .pub files
#############################
pubKeyHex="$(openssl ec -inform DER -text -noout -in <(cat <(echo -n "302e0201010420") <(echo -n "${privKeyHex}") <(echo -n "a00706052b8104000a") | xxd -r -p) 2>/dev/null | tail -6 | head -5 | sed 's/[ :]//g' | tr -d '\n')"
asnFormatKey="30740201010420${privKeyHex}a00706052b8104000aa144034200${pubKeyHex}"
echo "-----BEGIN EC PRIVATE KEY-----" > tmp.pem
echo $asnFormatKey | xxd -r -p | base64 | fold -w 64 >> tmp.pem
echo "-----END EC PRIVATE KEY-----" >> tmp.pem
openssl ec -in tmp.pem -pubout -out tmpPub.pem &>/dev/null
## Sign message
# sign:
openssl pkeyutl -sign -inkey tmp.pem -in <(printf $inputHex | xxd -r -p) -out tmp.sig
echo "Signature"
echo "####################"
echo ""
openssl pkeyutl -sign -inkey tmp.pem -in <(printf $inputHex | xxd -r -p) | xxd -p #-hexdump #| xxd -p
echo ""
echo "####################"
# verify:
openssl pkeyutl -verify -pubin -inkey tmpPub.pem -sigfile tmp.sig -in <(printf $inputHex | xxd -r -p)
rm tmp.pem tmpPub.pem tmp.sig
另请参阅:
这篇关于使用椭圆曲线secp256k1在命令行中对十六进制字符串进行数字签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!