jsonwebtoken/src/crypto/ecdsa.rs

39 lines
1.4 KiB
Rust
Raw Normal View History

2019-11-08 14:00:19 -05:00
use ring::{rand, signature};
2019-11-11 14:29:57 -05:00
use crate::algorithms::Algorithm;
2019-11-09 06:42:40 -05:00
use crate::errors::Result;
2019-11-11 14:16:34 -05:00
use crate::serialization::b64_encode;
/// Only used internally when validating EC, to map from our enum to the Ring EcdsaVerificationAlgorithm structs.
2019-11-11 14:29:57 -05:00
pub(crate) fn alg_to_ec_verification(
alg: Algorithm,
) -> &'static signature::EcdsaVerificationAlgorithm {
2019-11-11 14:16:34 -05:00
match alg {
Algorithm::ES256 => &signature::ECDSA_P256_SHA256_FIXED,
Algorithm::ES384 => &signature::ECDSA_P384_SHA384_FIXED,
2019-11-11 14:29:57 -05:00
_ => unreachable!("Tried to get EC alg for a non-EC algorithm"),
}
}
/// Only used internally when signing EC, to map from our enum to the Ring EcdsaVerificationAlgorithm structs.
pub(crate) fn alg_to_ec_signing(alg: Algorithm) -> &'static signature::EcdsaSigningAlgorithm {
match alg {
Algorithm::ES256 => &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
Algorithm::ES384 => &signature::ECDSA_P384_SHA384_FIXED_SIGNING,
_ => unreachable!("Tried to get EC alg for a non-EC algorithm"),
2019-11-11 14:16:34 -05:00
}
}
2019-11-08 14:00:19 -05:00
/// The actual ECDSA signing + encoding
2019-12-29 12:42:35 -05:00
/// The key needs to be in PKCS8 format
2019-11-08 14:00:19 -05:00
pub fn sign(
alg: &'static signature::EcdsaSigningAlgorithm,
key: &[u8],
2020-11-17 08:17:40 -05:00
message: &[u8],
2019-11-08 14:00:19 -05:00
) -> Result<String> {
2019-12-29 12:42:35 -05:00
let signing_key = signature::EcdsaKeyPair::from_pkcs8(alg, key)?;
2019-11-08 14:00:19 -05:00
let rng = rand::SystemRandom::new();
2020-11-17 08:17:40 -05:00
let out = signing_key.sign(&rng, message)?;
Ok(b64_encode(out))
2019-11-08 14:00:19 -05:00
}