mirleft / ocaml-x509

X509 (RFC5280) handling in OCaml
BSD 2-Clause "Simplified" License
52 stars 33 forks source link

RSA keys don't roundtrip? #171

Closed anmonteiro closed 1 month ago

anmonteiro commented 1 month ago

forgive me if this is a dumb mistake on my part, but take this example:

# generate RSA priv key
$ openssl genpkey -algorithm RSA -out privatekey.pem -pkeyopt rsa_keygen_bits:2048

# extract the public key
$ openssl pkey -in privatekey.pem -pubout -out publickey.pem

and in a toplevel (e.g. utop):

#require "digestif.c";;
#require "x509";;

let x_pub = In_channel.input_all (In_channel.open_bin "./publickey.pem");;

let re_encoded =X509.Public_key.decode_pem x_pub |> Result.get_ok |> X509.Public_key.encode_pem;;

x_pub = re_encoded (* false *)

I'd expect these to roundtrip. In the previous version of X509 (before the Cstruct -> string migration), they did roundtrip:

let re_encoded = X509.Public_key.decode_pem (Cstruct.of_string x_pub) |> Result.get_ok |> X509.Public_key.encode_pem |> Cstruct.to_string;;

x = x_pub;;
- : bool = true
hannesm commented 1 month ago

Thanks for your report, I opened #172 with a regression test and a fix. If you could verify that this fixes your issue, that would be great.

I'll wait for CI, then merge and release.

anmonteiro commented 1 month ago

Thanks, that fixed RSA, but I think I might be seeing the same for P521?

hannesm commented 1 month ago

@anmonteiro would you mind to open a PR with a regression test? thanks a lot.

hannesm commented 1 month ago

I'm asking since I tried to reproduce "the same for P521", but without luck. Even before I released 1.0.2.

Note that this package does not include the public key into the PKCS8 encoded private key dump, as openssl normally does (for reasons unknown to me). This means that a openssl generated private key file, read, decoded, encoded, and written by this package won't be identical - but the private key part is identical.

I pushed https://github.com/mirleft/ocaml-x509/pull/173 which includes all the P curve public and private key tests -- together with a shell script what openssl commands have been executed to generate the keypairs. WDYT?