From 4f0e42ad6fb646c4b503ff6024105bb8e84efb09 Mon Sep 17 00:00:00 2001 From: Ulrik Strid Date: Mon, 13 Feb 2023 15:28:55 +0100 Subject: [PATCH] Allow creating JWK from x509 keys directly --- jose/Jose.mli | 10 ++++++++++ jose/Jwk.ml | 17 +++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/jose/Jose.mli b/jose/Jose.mli index 1f6e714..b970cc5 100644 --- a/jose/Jose.mli +++ b/jose/Jose.mli @@ -163,6 +163,16 @@ module Jwk : sig (** [to_priv_pem t] takes a JWK and returns a result PEM string or a message of what went wrong. *) + val of_priv_x509 : + ?use:use -> + X509.Private_key.t -> + (priv t, [> `Msg of string | `Not_rsa ]) result + + val of_pub_x509 : + ?use:use -> + X509.Public_key.t -> + (public t, [> `Msg of string | `Not_rsa ]) result + val of_priv_json : Yojson.Safe.t -> ( priv t, diff --git a/jose/Jwk.ml b/jose/Jwk.ml index 9dc618f..827ae01 100644 --- a/jose/Jwk.ml +++ b/jose/Jwk.ml @@ -348,6 +348,23 @@ let to_priv_pem (jwk : priv t) = Ok (X509.Private_key.encode_pem (`RSA rsa.key) |> Cstruct.to_string) | _ -> Error `Not_rsa +let of_priv_x509 ?use x509 : (priv t, [> `Not_rsa ]) result = + match x509 with + | `RSA priv_key -> Ok (make_priv_rsa ?use priv_key) + | `P256 priv_key -> Ok (make_priv_es256 ?use priv_key) + | `P384 priv_key -> Ok (make_priv_es384 ?use priv_key) + | `P521 priv_key -> Ok (make_priv_es512 ?use priv_key) + | _ -> Error (`Msg "key type not supported") + +let of_pub_x509 ?use (x509 : X509.Public_key.t) : + (public t, [> `Not_rsa ]) result = + match x509 with + | `RSA public_key -> Ok (make_pub_rsa ?use public_key) + | `P256 public_key -> Ok (make_pub_es256 ?use public_key) + | `P384 public_key -> Ok (make_pub_es384 ?use public_key) + | `P521 public_key -> Ok (make_pub_es512 ?use public_key) + | _ -> Error (`Msg "key type not supported") + let oct_to_json (oct : oct) = let values = [