1use josekit::jwk::{alg::ec::EcCurve, Jwk};
2use serde::{Deserialize, Serialize};
3use std::hash::{Hash, Hasher};
4
5#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
11pub struct JWK(pub Jwk);
12
13impl JWK {
14 pub fn new() -> Result<Self, anyhow::Error> {
17 Ok(JWK(Jwk::generate_ec_key(EcCurve::P256)?))
18 }
19
20 pub fn new_from_bytes(bytes: &[u8]) -> Result<Self, anyhow::Error> {
22 Ok(JWK(Jwk::from_bytes(bytes)?))
23 }
24
25 pub fn to_public_only(&self) -> Result<Self, anyhow::Error> {
27 Ok(JWK(self.0.to_public_key()?))
28 }
29}
30
31impl Serialize for JWK {
32 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
33 where
34 S: serde::Serializer,
35 {
36 match self.to_public_only() {
37 Ok(public) => public.0.serialize(serializer),
38 Err(e) => Err(serde::ser::Error::custom(e)),
39 }
40 }
41}
42
43impl Hash for JWK {
44 fn hash<H: Hasher>(&self, state: &mut H) {
45 self.0.key_id().hash(state)
46 }
47}
48
49impl PartialOrd for JWK {
50 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
51 let mut state = std::collections::hash_map::DefaultHasher::default();
52 let mut other_state = std::collections::hash_map::DefaultHasher::default();
53 self.hash(&mut state);
54 other.hash(&mut other_state);
55
56 state.finish().partial_cmp(&other_state.finish())
57 }
58}
59
60impl Ord for JWK {
61 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
62 self.partial_cmp(other).unwrap()
63 }
64}