Tuesday, February 23, 2010

Reading an openssl .priv.key file and extracting the key

Extracting the private key from a .priv.key file is simple.
The private key is encrypted using a AES-128 with your passphrase.

The initial vector is also stored in the file, you can extract it directly from the first line:
get_salt( <<"Salted__", Salt:8/binary, Rest/binary>> ) ->
        {Salt, Rest}.

The last part is handled by some md5() of your passphrase and the initial vector:
Key = crypto:md5([ Password, Salt ]),
        IV = crypto:md5([ Key, Password, Salt ]),
        crypto:aes_cbc_128_decrypt( Key, IV, Rest).


Now the full module:
-module(priv_key).

-compile(export_all).

priv_key_file( File, Password ) ->
        {ok, Bin} = file:read_file(File),
        {Salt, Rest} = get_salt(Bin),
        Key = crypto:md5([ Password, Salt ]),
        IV = crypto:md5([ Key, Password, Salt ]),
        crypto:aes_cbc_128_decrypt( Key, IV, Rest).
        
get_salt( <<"Salted__", Salt:8/binary, Rest/binary>> ) ->
        {Salt, Rest}.

No comments:

Sticky