【问题标题】:How should I use crypto:sign/4 properly?我应该如何正确使用 crypto:sign/4?
【发布时间】:2013-08-06 11:24:52
【问题描述】:

我尝试使用 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.

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

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)

感谢 Paul,通过以下更改可以修复此错误。

改变:

SigBin = crypto:sign(Algorithm, DigestType, MsgBin, PriKey),

到:

SigBin = crypto:sign(Algorithm, DigestType, MsgBin, [PriKey, secp256k1]),

【问题讨论】:

    标签: encryption erlang sign ecdsa


    【解决方案1】:

    crypto:sign/4 和 crypto:generate_key/2 函数对于 ECDSA 来说相当混乱,因为 ECDSA 需要域参数,这与其他两种受支持的算法不同。

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

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

    文档内容如下:

    sign(Algorithm, DigestType, Msg, Key) -&gt; binary()

    类型:

    Algorithm = rsa | dss | ecdsa

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

    消息要么是要签名的二进制“明文”数据,要么是“明文”的散列值,即摘要(明文)。

    DigestType = digest_type()

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

    你的前三个参数显然没问题。问题在于钥匙。事实上,你的代码是这样的:

    {_PubKey, PriKey} = crypto:generate_key(ecdh, secp256k1)
    

    查看crypto:generate_key/2 的文档,您会发现在ECDH 的情况下,PrivKey 的类型为ecdh_private(),而不是[ecdh_private(),ecdh_params()],正如crypto:sign/4 所期望的那样。

    解决方法是将[PrivKey, secp256k1] 传递给您的sign_message 函数,因为符号函数需要通过符号键参数识别曲线域参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-02
      • 2021-12-03
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      相关资源
      最近更新 更多