[erlang-questions] rsa encryption/decryption example code doesn't work

Chad DePue chad@REDACTED
Sun Jun 28 15:07:54 CEST 2009


Thanks, Rich - that did it. Here's the final code.

-module(crypttest).
-include_lib("public_key/include/public_key.hrl").
-export([testcase/0]).


testcase() ->
   {ok,[Entry]} = public_key:pem_to_der("./test_private_key"),
   {ok,{'RSAPrivateKey', 'two-prime', N , E, D, _P, _Q, _E1, _E2, _C,  
_Other}} =  public_key:decode_private_key(Entry),
   PlainText = "now is the time for all good men to come to the aid of  
their country",
   PrivKey = [crypto:mpint(E), crypto:mpint(N), crypto:mpint(D)] ,
   PubKey = [crypto:mpint(E), crypto:mpint(N)],
   Foo =  
crypto:rsa_private_encrypt(PlainText,PrivKey,rsa_pkcs1_padding),
   Bar = crypto:rsa_public_decrypt(Foo,PubKey,rsa_pkcs1_padding),
   PlainText == binary_to_list(Bar).

7> c(crypttest).
{ok,crypttest}
8> crypttest:testcase().
true


On Jun 28, 2009, at 7:09 AM, Richard Andrews wrote:

> On Sun, Jun 28, 2009 at 7:52 AM, Chad DePue<chad@REDACTED>  
> wrote:
>> I have written this sample rsa encryption code and it doesn't decrypt
>> properly.  I generated the test private key using ssh-keygen. any  
>> ideas?
>> thanks in advance...
>>
>> chad
>>
>>
>> -module(crypttest).
>> -include_lib("public_key/include/public_key.hrl").
>> -export([testcase/0]).
>>
>> testcase() ->
>>  {ok,[Entry]} = public_key:pem_to_der("./test_private_key"),
>>  {ok,{'RSAPrivateKey', 'two-prime', N , E, D, _P, _Q, _E1, _E2, _C,  
>> _Other}}
>> =  public_key:decode_private_key(Entry),
>>  PrivKey = [crypto:mpint(E), crypto:mpint(N), crypto:mpint(D)] ,
>>  Foo = crypto:rsa_private_encrypt("now is the time for all good men  
>> to come
>> to the aid of their country",PrivKey,rsa_pkcs1_padding),
>>  Bar = crypto:rsa_private_decrypt(Foo,PrivKey,rsa_pkcs1_padding),
>>  Foo == Bar.
>
> For asymmetric encryption, one generally encrypts with one key and
> decrypts with the other. In this case you are encrypting with PrivKey
> so you will need to decrypt with PubKey.
>
> --
>  Rich



More information about the erlang-questions mailing list