我应该如何正确使用加密:sign/4?

Nin*_*ing 1 encryption erlang sign ecdsa

我尝试使用crypto:sign/4来签名但是失败了.任何人都可以告诉我如何在Erlang中使用ECDSA签名消息吗?谢谢.(我使用的是Erlang版R16B01.)

模块代码:

-module(message).

-compile(export_all).

go() ->
    {_PubKey, PriKey} = crypto:generate_key(ecdh, secp256k1),
    SigBin = sign_message(PriKey, "Hello"),
    SigBin.

sign_message(PriKey, Msg) ->
    Algorithm = ecdsa,
    DigestType = sha256,
    MsgBin = list_to_binary(Msg),
    SigBin = crypto:sign(Algorithm, DigestType, MsgBin, PriKey),
    SigBin.
Run Code Online (Sandbox Code Playgroud)

但它在测试运行中失败了:

1> message:go().
** exception error: no function clause matching crypto:sign(ecdsa,sha256,
                                                        {digest,

        <<24,95,141,179,34,113,254,37,245,97,166,252,147,
        139,46,38,67,6,236,48,78,218,81,128,...>>},
        <<189,38,200,204,95,248,54,69,42,65,216,165,242,228,100,
        54,158,5,61,174,58,198,191,161,9,...>>) (crypto.erl, line 462)
Run Code Online (Sandbox Code Playgroud)

感谢Paul,可以通过进行以下更改来解决此错误.

更改:

SigBin = crypto:sign(Algorithm, DigestType, MsgBin, PriKey),
Run Code Online (Sandbox Code Playgroud)

至:

SigBin = crypto:sign(Algorithm, DigestType, MsgBin, [PriKey, secp256k1]),
Run Code Online (Sandbox Code Playgroud)

Pau*_*yot 6

对于ECDSA而言,这些crypto:sign/4crypto:generate_key/2函数非常混乱,因为ECDSA需要域参数,这与其他两种支持的算法不同.

错误消息只是告诉您传递的参数与crypto:sign/4函数的任何子句都不匹配.您可能正在传递错误类型的参数.

您可以查看被调用函数的源代码,找出没有子句与您的参数匹配的原因.这通常是您为自己的功能所做的事情.然而,这里crypto:sign/4是一个正确记录的系统功能.

文件内容如下:

sign(Algorithm, DigestType, Msg, Key) -> binary()

类型:

Algorithm = rsa | dss | ecdsa

Msg = binary() | {digest,binary()}

msg是要签名的二进制"明文"数据,或者是"明文"的散列值,即摘要(明文).

DigestType = digest_type()

Key = rsa_private() | dss_private() | [ecdh_private(),ecdh_params()]

你的前三个论点显然没问题.问题在于密钥.的确,你的代码是这样的:

{_PubKey, PriKey} = crypto:generate_key(ecdh, secp256k1)
Run Code Online (Sandbox Code Playgroud)

望着的文档crypto:generate_key/2,你会发现,在ECDH的情况下,PrivKey是类型的ecdh_private(),而不是[ecdh_private(),ecdh_params()]crypto:sign/4预期.

修复将传递[PrivKey, secp256k1]给您的sign_message函数,因为符号函数需要通过符号键参数识别曲线域参数.