[erlang-questions] Crypto and public_key usage....

Seth Falcon seth@REDACTED
Thu Apr 14 17:49:14 CEST 2011

Hi Peter,

On Thu, Apr 14, 2011 at 7:55 AM, Peter W. Morreale <pmorreale@REDACTED> wrote:
> I'm attempting to use the crypto and public key modules to decrypt
> an encrypted response I get in a server.
> I found this
> http://erlang.2086793.n4.nabble.com/rsa-encryption-decryption-example-code-doesn-t-work-td2114965.html
> example on the web, however in my case, I already have the public key as
> a string.

If your string represents an RSA public key in SubjectPublicKeyInfo
PEM format and you are using the latest Erlang release, I think you
can obtain the key record that you can use in the encrypt/decrpyt
functions in the public_key module as follows:

    {ok, RSAPubPem} = file:read_file("rsa_pub.pem"),
    PemEntries = public_key:pem_decode(RSAPubPem),
    RSAPubKey = public_key:pem_entry_decode(hd(PemEntries)),
    % now use RSAPubKey to decrypt/encrypt

You will have a few more hoops to jump through for older versions of
Erlang.  Here's one way:

    read_rsa_public_key(Key) ->
        Bin = erlang:iolist_to_binary(public_key_lines(re:split(Key,
"\n"), [])),
        Spki = public_key:der_decode('SubjectPublicKeyInfo',
        {_, _, {0, KeyDer}} = Spki,
        public_key:der_decode('RSAPublicKey', KeyDer).

    public_key_lines([<<"-----BEGIN PUBLIC KEY-----">>|Rest], Acc) ->
        public_key_lines(Rest, Acc);
    public_key_lines([<<"-----END PUBLIC KEY-----">>|_Rest], Acc) ->
    public_key_lines([Line|Rest], Acc) ->
        public_key_lines(Rest, [Line|Acc]).

If this isn't what you are looking for, it would be helpful to provide
more detail on the type of key you have and what you want to do with

+ seth

Seth Falcon | @sfalcon | http://userprimary.net/

More information about the erlang-questions mailing list