Digitally sign a hex string in command line using elliptic curve secp256k1

房东的猫 提交于 2021-01-28 06:51:40

问题


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.

Example:

  • string to sign: 1333183ddf384da83ed49296136c70d206ad2b19331bf25d390e69b222165e37
  • private key: a675c86089e0622c112379906f5cf19ee336575af1bfa1de558051312db9afdc

Hoping there is a command like:

$ openssl sign -msg=1333183ddf384da83ed49296136c70d206ad2b19331bf25d390e69b222165e37 -privkey=a675c86089e0622c112379906f5cf19ee336575af1bfa1de558051312db9afdc

回答1:


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).

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

See also:

  • How to convert an ECDSA key to PEM format
  • Signing transaction with SSL - private key to PEM


来源:https://stackoverflow.com/questions/51845590/digitally-sign-a-hex-string-in-command-line-using-elliptic-curve-secp256k1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!