Skip to content

Commit

Permalink
added an example for ed25519 (#282)
Browse files Browse the repository at this point in the history
Co-authored-by: Ovidiu Ionescu <ovidiu@ionescu.net>
  • Loading branch information
ovidiu-ionescu and ovidiu-ionescu committed Jan 6, 2023
1 parent 708d452 commit d2ba351
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions examples/ed25519.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
use jsonwebtoken::{
decode, encode, get_current_timestamp, Algorithm, DecodingKey, EncodingKey, Validation,
};
use ring::signature::{Ed25519KeyPair, KeyPair};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
sub: String,
exp: u64,
}

fn main() {
let doc = Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()).unwrap();
let encoding_key = EncodingKey::from_ed_der(doc.as_ref());

let pair = Ed25519KeyPair::from_pkcs8(doc.as_ref()).unwrap();
let decoding_key = DecodingKey::from_ed_der(pair.public_key().as_ref());

let claims = Claims { sub: "test".to_string(), exp: get_current_timestamp() };

let token =
encode(&jsonwebtoken::Header::new(Algorithm::EdDSA), &claims, &encoding_key).unwrap();

let validation = Validation::new(Algorithm::EdDSA);
let _token_data = decode::<Claims>(&token, &decoding_key, &validation).unwrap();
}

#[cfg(test)]
mod tests {
use super::*;

struct Jot {
encoding_key: EncodingKey,
decoding_key: DecodingKey,
}

impl Jot {
fn new() -> Jot {
let doc = Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()).unwrap();
let encoding_key = EncodingKey::from_ed_der(doc.as_ref());

let pair = Ed25519KeyPair::from_pkcs8(doc.as_ref()).unwrap();
let decoding_key = DecodingKey::from_ed_der(pair.public_key().as_ref());
Jot { encoding_key, decoding_key }
}
}

#[test]
fn test() {
let jot = Jot::new();
let claims = Claims { sub: "test".to_string(), exp: get_current_timestamp() };

let token =
encode(&jsonwebtoken::Header::new(Algorithm::EdDSA), &claims, &jot.encoding_key)
.unwrap();

let validation = Validation::new(Algorithm::EdDSA);
let token_data = decode::<Claims>(&token, &jot.decoding_key, &validation).unwrap();
assert_eq!(token_data.claims.sub, "test");
}
}

0 comments on commit d2ba351

Please sign in to comment.