[erlang-questions] Using public_key:sign/3 gives error badkey (crypto.erl, line 852)

Paul Cager paul.cager@REDACTED
Wed Apr 3 14:18:12 CEST 2013


I can successfully RSA sign a message using lower-level functions such as 
crypto:mpint, crypto:rsa_private_encrypt (e.g. as in the samples at 
http://lj.rossia.org/users/eacher/2013/01/07/).

However I'd prefer to use what looks like higher-level functions in the 
public_key module but I'm not sure what I'm doing wrong. The following 
sample program fails with "badkey" - any ideas what is wrong?

(Erlang R16B)

-module(test_crypto).

-compile(export_all).

-include_lib("public_key/include/public_key.hrl").
-include_lib("eunit/include/eunit.hrl").

-define(TEST_DATA, <<"Test">>).

sign_test() ->
    application:start(crypto),
    [Entry] = public_key:pem_decode(test_priv_key()),
    PrivateKey = public_key:pem_entry_decode(Entry),
    ?assert(is_record(PrivateKey, 'RSAPrivateKey')),

    #'RSAPrivateKey'{ modulus = N, publicExponent = E, privateExponent = D} 
= PrivateKey,

    io:format("Decoded: ~p~n  N=~p~n  E=~p~n  D=~p~n", [PrivateKey, N, E, 
D]),

    Signed = public_key:sign(?TEST_DATA, md5, PrivateKey),

    io:format("signed: ~p~n", [Signed]),

    error(force_failure).


test_priv_key() ->
    iolist_to_binary([
        "-----BEGIN RSA PRIVATE KEY-----", $\n,
        "MIGqAgEAAiEAsfQgn015/7zGm2Hy0wh28voJTcDM5vXbQIb47IRvPkECAwEAAQIg", 
$\n,
        "Ibi0Udu5qaeZLyqxfCIXgATS+x7mDA0tMJXtheJCkUECEQDWLuQfQZJEJOZq05eM", 
$\n,
        "EFypAhEA1LJxrD0/ZVA8u7FSlV/72QIRALr5BkXO3RvFxqv8+K/Z3LkCEBQpJeUx", 
$\n,
        "mQS9akRQNoe6JWECEDR94PUjkOWSkZrCwpsXbbg=", $\n,
        "-----END RSA PRIVATE KEY-----", $\n]).

test_pub_key() ->
    iolist_to_binary([
        "-----BEGIN PUBLIC KEY-----", $\n,
        "MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhALH0IJ9Nef+8xpth8tMIdvL6CU3AzOb1", 
$\n,
        "20CG+OyEbz5BAgMBAAE=", $\n,
        "-----END PUBLIC KEY-----", $\n]).

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20130403/e28e5195/attachment.htm>


More information about the erlang-questions mailing list