[erlang-questions] public_key & OpenSSL format weirdness

zxq9 zxq9@REDACTED
Thu Feb 26 03:01:22 CET 2015

On 2015年2月26日 木曜日 10:56:32 zxq9 wrote:
> I have encountered a strange issue with the public_key and crypto modules
> regarding RSA key formats generated by OpenSSL.
> If I generate a private key in PEM format, public_key:pem_entry_decode/1
> will not return an #'RSAPrivateKey'{} record, but if I generate the private
> key in DER format public_key:der_decode('RSAPrivateKey', KeyFile) will
> return the correct #'RSAPrivateKey'{}.
> Conversely, if I generate the public key in DER format
> public_key:der_decode('RSAPublicKey', PubFile) will give me an asn1 error,
> but if I generate the public key in PEM format
> public_key:pem_entry_decode/1 returns the correct #'RSAPublicKey'{} record.
> If I go one step further and decode the public key from a PEM file, then use
> public_key:der_encode/2 and write the resulting binary to a file as DER,
> then I can use the Erlang-generated DER of the public key with no problem.
> The I'm using "OpenSSL 1.0.1f 6 Jan 2014" on Linux.

Comparing the OpenSSL generated DER and the Erlang generated DER, I found 

ceverett@REDACTED:~/Code/erlang/keytest$ cp rsa3.pub.der rsa3.pub.der.erlang
ceverett@REDACTED:~/Code/erlang/keytest$ openssl rsa -inform DER -in 
rsa3.key.der -outform DER -pubout -out rsa3.pub.der.openssl
writing RSA key
ceverett@REDACTED:~/Code/erlang/keytest$ ls -l rsa3.pub.der.{erlang,openssl}
-rw-rw-r-- 1 ceverett ceverett 1038  2月 26 10:58 rsa3.pub.der.erlang
-rw-rw-r-- 1 ceverett ceverett 1062  2月 26 10:58 rsa3.pub.der.openssl
ceverett@REDACTED:~/Code/erlang/keytest$ cmp -b rsa3.pub.der.erlang 
rsa3.pub.der.erlang rsa3.pub.der.openssl 異なります: バイト 4、行 1  12 ^J  42 "
ceverett@REDACTED:~/Code/erlang/keytest$ cmp -b --ignore-initial=0:24 
rsa3.pub.der.erlang rsa3.pub.der.openssl
ceverett@REDACTED:~/Code/erlang/keytest$ erl
Erlang/OTP 17 [erts-6.3] [source] [64-bit] [smp:2:2] [async-threads:10] 

Running $HOME/.erlang.
Eshell V6.3  (abort with ^G)
1> {ok, OpenSSLBin} = file:read_file("rsa3.pub.der.openssl").
2> {ok, ErlangBin} = file:read_file("rsa3.pub.der.erlang").
3> <<_:24/binary, ChoppedBin/binary>> = OpenSSLBin.
4> ChoppedBin = ErlangBin.

So it appears there are 24 extra bytes appended to the OpenSSL generated DER 
that are confusing the asn1 import function, but only in the case of public 
RSA keys, as private OpenSSL generated DER keys match what is expected.

More information about the erlang-questions mailing list