fix(servo): gate vulnerable RSA private operations
This commit is contained in:
+307
@@ -0,0 +1,307 @@
|
||||
use super::{sign_digest, Signature, VerifyingKey};
|
||||
use crate::{Result, RsaPrivateKey};
|
||||
use core::marker::PhantomData;
|
||||
use digest::{Digest, FixedOutputReset, HashMarker, Update};
|
||||
use rand_core::{CryptoRng, TryCryptoRng};
|
||||
use signature::{
|
||||
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedMultipartSigner,
|
||||
RandomizedSigner,
|
||||
};
|
||||
use zeroize::ZeroizeOnDrop;
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
use {
|
||||
super::get_pss_signature_algo_id,
|
||||
const_oid::AssociatedOid,
|
||||
pkcs8::{EncodePrivateKey, SecretDocument},
|
||||
spki::{
|
||||
der::AnyRef, AlgorithmIdentifierOwned, AlgorithmIdentifierRef,
|
||||
AssociatedAlgorithmIdentifier, DynSignatureAlgorithmIdentifier,
|
||||
},
|
||||
};
|
||||
#[cfg(feature = "serde")]
|
||||
use {
|
||||
pkcs8::DecodePrivateKey,
|
||||
serdect::serde::{de, ser, Deserialize, Serialize},
|
||||
};
|
||||
|
||||
/// Signing key for producing "blinded" RSASSA-PSS signatures as described in
|
||||
/// [draft-irtf-cfrg-rsa-blind-signatures](https://datatracker.ietf.org/doc/draft-irtf-cfrg-rsa-blind-signatures/).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
inner: RsaPrivateKey,
|
||||
salt_len: usize,
|
||||
phantom: PhantomData<D>,
|
||||
}
|
||||
|
||||
impl<D> BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
/// Create a new RSASSA-PSS signing key which produces "blinded"
|
||||
/// signatures.
|
||||
/// Digest output size is used as a salt length.
|
||||
pub fn new(key: RsaPrivateKey) -> Self {
|
||||
Self::new_with_salt_len(key, <D as Digest>::output_size())
|
||||
}
|
||||
|
||||
/// Create a new RSASSA-PSS signing key which produces "blinded"
|
||||
/// signatures with a salt of the given length.
|
||||
pub fn new_with_salt_len(key: RsaPrivateKey, salt_len: usize) -> Self {
|
||||
Self {
|
||||
inner: key,
|
||||
salt_len,
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new random RSASSA-PSS signing key which produces "blinded"
|
||||
/// signatures.
|
||||
/// Digest output size is used as a salt length.
|
||||
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
|
||||
Self::random_with_salt_len(rng, bit_size, <D as Digest>::output_size())
|
||||
}
|
||||
|
||||
/// Create a new random RSASSA-PSS signing key which produces "blinded"
|
||||
/// signatures with a salt of the given length.
|
||||
pub fn random_with_salt_len<R: CryptoRng + ?Sized>(
|
||||
rng: &mut R,
|
||||
bit_size: usize,
|
||||
salt_len: usize,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: RsaPrivateKey::new(rng, bit_size)?,
|
||||
salt_len,
|
||||
phantom: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Return specified salt length for this key
|
||||
pub fn salt_len(&self) -> usize {
|
||||
self.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// `*Signer` trait impls
|
||||
//
|
||||
|
||||
impl<D> RandomizedSigner<Signature> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
msg: &[u8],
|
||||
) -> signature::Result<Signature> {
|
||||
self.try_multipart_sign_with_rng(rng, &[msg])
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedMultipartSigner<Signature> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn try_multipart_sign_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
msg: &[&[u8]],
|
||||
) -> signature::Result<Signature> {
|
||||
let mut digest = D::new();
|
||||
msg.iter()
|
||||
.for_each(|slice| <D as Digest>::update(&mut digest, slice));
|
||||
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Default + FixedOutputReset + HashMarker + Update,
|
||||
{
|
||||
fn try_sign_digest_with_rng<
|
||||
R: TryCryptoRng + ?Sized,
|
||||
F: Fn(&mut D) -> signature::Result<()>,
|
||||
>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
f: F,
|
||||
) -> signature::Result<Signature> {
|
||||
let mut digest = D::default();
|
||||
f(&mut digest)?;
|
||||
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
prehash: &[u8],
|
||||
) -> signature::Result<Signature> {
|
||||
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Other trait impls
|
||||
//
|
||||
|
||||
impl<D> AsRef<RsaPrivateKey> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn as_ref(&self) -> &RsaPrivateKey {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> AssociatedAlgorithmIdentifier for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
type Params = AnyRef<'static>;
|
||||
|
||||
const ALGORITHM_IDENTIFIER: AlgorithmIdentifierRef<'static> = pkcs1::ALGORITHM_ID;
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> DynSignatureAlgorithmIdentifier for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
fn signature_algorithm_identifier(&self) -> spki::Result<AlgorithmIdentifierOwned> {
|
||||
get_pss_signature_algo_id::<D>(self.salt_len as u8)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> EncodePrivateKey for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn to_pkcs8_der(&self) -> pkcs8::Result<SecretDocument> {
|
||||
self.inner.to_pkcs8_der()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<RsaPrivateKey> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: RsaPrivateKey) -> Self {
|
||||
Self::new(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<BlindedSigningKey<D>> for RsaPrivateKey
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: BlindedSigningKey<D>) -> Self {
|
||||
key.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Keypair for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
type VerifyingKey = VerifyingKey<D>;
|
||||
fn verifying_key(&self) -> Self::VerifyingKey {
|
||||
VerifyingKey {
|
||||
inner: self.inner.to_public_key(),
|
||||
salt_len: Some(self.salt_len),
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> TryFrom<pkcs8::PrivateKeyInfoRef<'_>> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
type Error = pkcs8::Error;
|
||||
|
||||
fn try_from(private_key_info: pkcs8::PrivateKeyInfoRef<'_>) -> pkcs8::Result<Self> {
|
||||
RsaPrivateKey::try_from(private_key_info).map(Self::new)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> ZeroizeOnDrop for BlindedSigningKey<D> where D: Digest {}
|
||||
|
||||
impl<D> PartialEq for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inner == other.inner && self.salt_len == other.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<D> Serialize for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let der = self.to_pkcs8_der().map_err(ser::Error::custom)?;
|
||||
serdect::slice::serialize_hex_lower_or_bin(&der.as_bytes(), serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, D> Deserialize<'de> for BlindedSigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
fn deserialize<De>(deserializer: De) -> core::result::Result<Self, De::Error>
|
||||
where
|
||||
De: serde::Deserializer<'de>,
|
||||
{
|
||||
let der_bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
|
||||
Self::from_pkcs8_der(&der_bytes).map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
#[cfg(all(feature = "hazmat", feature = "serde"))]
|
||||
fn test_serde() {
|
||||
use super::*;
|
||||
use rand::rngs::ChaCha8Rng;
|
||||
use rand_core::SeedableRng;
|
||||
use serde_test::{assert_tokens, Configure, Token};
|
||||
use sha2::Sha256;
|
||||
|
||||
let mut rng = ChaCha8Rng::from_seed([42; 32]);
|
||||
let signing_key = BlindedSigningKey::<Sha256>::new(
|
||||
RsaPrivateKey::new_unchecked(&mut rng, 64).expect("failed to generate key"),
|
||||
);
|
||||
|
||||
let tokens = [Token::Str(concat!(
|
||||
"3056020100300d06092a864886f70d010101050004423040020100020900ab240c",
|
||||
"3361d02e370203010001020811e54a15259d22f9020500ceff5cf3020500d3a7aa",
|
||||
"ad020500ccaddf17020500cb529d3d020500bb526d6f"
|
||||
))];
|
||||
assert_tokens(&signing_key.readable(), &tokens);
|
||||
}
|
||||
}
|
||||
Vendored
+106
@@ -0,0 +1,106 @@
|
||||
//! `RSASSA-PSS` signatures.
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
|
||||
use crypto_bigint::BoxedUint;
|
||||
use signature::SignatureEncoding;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serdect::serde::{de, Deserialize, Serialize};
|
||||
#[cfg(feature = "encoding")]
|
||||
use spki::{
|
||||
der::{asn1::BitString, Result as DerResult},
|
||||
SignatureBitStringEncoding,
|
||||
};
|
||||
|
||||
/// `RSASSA-PSS` signatures as described in [RFC8017 § 8.1].
|
||||
///
|
||||
/// [RFC8017 § 8.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.1
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Signature {
|
||||
pub(super) inner: BoxedUint,
|
||||
}
|
||||
|
||||
impl SignatureEncoding for Signature {
|
||||
type Repr = Box<[u8]>;
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl SignatureBitStringEncoding for Signature {
|
||||
fn to_bitstring(&self) -> DerResult<BitString> {
|
||||
BitString::new(0, self.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&[u8]> for Signature {
|
||||
type Error = signature::Error;
|
||||
|
||||
fn try_from(bytes: &[u8]) -> signature::Result<Self> {
|
||||
// TODO(tarcieri): max length restriction? (#350)
|
||||
let inner = BoxedUint::from_be_slice_vartime(bytes);
|
||||
Ok(Self { inner })
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Signature> for Box<[u8]> {
|
||||
fn from(signature: Signature) -> Box<[u8]> {
|
||||
signature.inner.to_be_bytes()
|
||||
}
|
||||
}
|
||||
|
||||
impl LowerHex for Signature {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:x}", &self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl UpperHex for Signature {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:X}", &self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for Signature {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
|
||||
write!(f, "{:X}", self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl Serialize for Signature {
|
||||
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serdect::serde::Serializer,
|
||||
{
|
||||
serdect::slice::serialize_hex_lower_or_bin(&self.to_bytes(), serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de> Deserialize<'de> for Signature {
|
||||
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
|
||||
where
|
||||
D: serdect::serde::Deserializer<'de>,
|
||||
{
|
||||
serdect::slice::deserialize_hex_or_bin_vec(deserializer)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
#[cfg(feature = "serde")]
|
||||
fn test_serde() {
|
||||
use super::*;
|
||||
use serde_test::{assert_tokens, Configure, Token};
|
||||
let signature = Signature {
|
||||
inner: BoxedUint::from(42u32),
|
||||
};
|
||||
|
||||
let tokens = [Token::Str("000000000000002a")];
|
||||
assert_tokens(&signature.readable(), &tokens);
|
||||
}
|
||||
}
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
use super::{sign_digest, Signature, VerifyingKey};
|
||||
use crate::{Result, RsaPrivateKey};
|
||||
use core::marker::PhantomData;
|
||||
use digest::{Digest, FixedOutputReset, Update};
|
||||
use rand_core::{CryptoRng, TryCryptoRng};
|
||||
use signature::{
|
||||
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedMultipartSigner,
|
||||
RandomizedSigner,
|
||||
};
|
||||
use zeroize::ZeroizeOnDrop;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use {
|
||||
pkcs8::DecodePrivateKey,
|
||||
serdect::serde::{de, ser, Deserialize, Serialize},
|
||||
};
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
use {
|
||||
super::get_pss_signature_algo_id,
|
||||
crate::encoding::verify_algorithm_id,
|
||||
const_oid::AssociatedOid,
|
||||
pkcs8::{EncodePrivateKey, SecretDocument},
|
||||
spki::{
|
||||
der::AnyRef, AlgorithmIdentifierOwned, AlgorithmIdentifierRef,
|
||||
AssociatedAlgorithmIdentifier, DynSignatureAlgorithmIdentifier,
|
||||
},
|
||||
};
|
||||
|
||||
#[cfg(feature = "getrandom")]
|
||||
use {
|
||||
crypto_common::getrandom::SysRng,
|
||||
signature::{hazmat::PrehashSigner, MultipartSigner, Signer},
|
||||
};
|
||||
|
||||
/// Signing key for producing RSASSA-PSS signatures as described in
|
||||
/// [RFC8017 § 8.1].
|
||||
///
|
||||
/// [RFC8017 § 8.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.1
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
inner: RsaPrivateKey,
|
||||
salt_len: usize,
|
||||
phantom: PhantomData<D>,
|
||||
}
|
||||
|
||||
impl<D> SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
/// Create a new RSASSA-PSS signing key.
|
||||
/// Digest output size is used as a salt length.
|
||||
pub fn new(key: RsaPrivateKey) -> Self {
|
||||
Self::new_with_salt_len(key, <D as Digest>::output_size())
|
||||
}
|
||||
|
||||
/// Create a new RSASSA-PSS signing key with a salt of the given length.
|
||||
pub fn new_with_salt_len(key: RsaPrivateKey, salt_len: usize) -> Self {
|
||||
Self {
|
||||
inner: key,
|
||||
salt_len,
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate a new random RSASSA-PSS signing key.
|
||||
/// Digest output size is used as a salt length.
|
||||
pub fn random<R: CryptoRng + ?Sized>(rng: &mut R, bit_size: usize) -> Result<Self> {
|
||||
Self::random_with_salt_len(rng, bit_size, <D as Digest>::output_size())
|
||||
}
|
||||
|
||||
/// Generate a new random RSASSA-PSS signing key with a salt of the given length.
|
||||
pub fn random_with_salt_len<R: CryptoRng + ?Sized>(
|
||||
rng: &mut R,
|
||||
bit_size: usize,
|
||||
salt_len: usize,
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
inner: RsaPrivateKey::new(rng, bit_size)?,
|
||||
salt_len,
|
||||
phantom: Default::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Return specified salt length for this key
|
||||
pub fn salt_len(&self) -> usize {
|
||||
self.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// `*Signer` trait impls
|
||||
//
|
||||
|
||||
impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset + Update,
|
||||
{
|
||||
fn try_sign_digest_with_rng<
|
||||
R: TryCryptoRng + ?Sized,
|
||||
F: Fn(&mut D) -> signature::Result<()>,
|
||||
>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
f: F,
|
||||
) -> signature::Result<Signature> {
|
||||
let mut digest = D::new();
|
||||
f(&mut digest)?;
|
||||
sign_digest::<_, D>(rng, false, &self.inner, &digest.finalize(), self.salt_len)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedSigner<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset + Update,
|
||||
{
|
||||
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
msg: &[u8],
|
||||
) -> signature::Result<Signature> {
|
||||
self.try_sign_digest_with_rng(rng, |digest: &mut D| {
|
||||
Update::update(digest, msg);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedMultipartSigner<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset + Update,
|
||||
{
|
||||
fn try_multipart_sign_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
msg: &[&[u8]],
|
||||
) -> signature::Result<Signature> {
|
||||
self.try_sign_digest_with_rng(rng, |digest: &mut D| {
|
||||
msg.iter().for_each(|slice| Update::update(digest, slice));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> RandomizedPrehashSigner<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset + Update,
|
||||
{
|
||||
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
|
||||
&self,
|
||||
rng: &mut R,
|
||||
prehash: &[u8],
|
||||
) -> signature::Result<Signature> {
|
||||
sign_digest::<_, D>(rng, false, &self.inner, prehash, self.salt_len)?
|
||||
.as_slice()
|
||||
.try_into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "getrandom")]
|
||||
impl<D> PrehashSigner<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
|
||||
self.sign_prehash_with_rng(&mut SysRng, prehash)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "getrandom")]
|
||||
impl<D> Signer<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
|
||||
self.try_sign_with_rng(&mut SysRng, msg)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "getrandom")]
|
||||
impl<D> MultipartSigner<Signature> for SigningKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn try_multipart_sign(&self, msg: &[&[u8]]) -> signature::Result<Signature> {
|
||||
self.try_multipart_sign_with_rng(&mut SysRng, msg)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Other trait impls
|
||||
//
|
||||
|
||||
impl<D> AsRef<RsaPrivateKey> for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn as_ref(&self) -> &RsaPrivateKey {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> AssociatedAlgorithmIdentifier for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
type Params = AnyRef<'static>;
|
||||
|
||||
const ALGORITHM_IDENTIFIER: AlgorithmIdentifierRef<'static> = pkcs1::ALGORITHM_ID;
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> DynSignatureAlgorithmIdentifier for SigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
fn signature_algorithm_identifier(&self) -> spki::Result<AlgorithmIdentifierOwned> {
|
||||
get_pss_signature_algo_id::<D>(self.salt_len as u8)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> EncodePrivateKey for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn to_pkcs8_der(&self) -> pkcs8::Result<SecretDocument> {
|
||||
self.inner.to_pkcs8_der()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<RsaPrivateKey> for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: RsaPrivateKey) -> Self {
|
||||
Self::new(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<SigningKey<D>> for RsaPrivateKey
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: SigningKey<D>) -> Self {
|
||||
key.inner
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Keypair for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
type VerifyingKey = VerifyingKey<D>;
|
||||
fn verifying_key(&self) -> Self::VerifyingKey {
|
||||
VerifyingKey {
|
||||
inner: self.inner.to_public_key(),
|
||||
salt_len: Some(self.salt_len),
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> TryFrom<pkcs8::PrivateKeyInfoRef<'_>> for SigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
type Error = pkcs8::Error;
|
||||
|
||||
fn try_from(private_key_info: pkcs8::PrivateKeyInfoRef<'_>) -> pkcs8::Result<Self> {
|
||||
verify_algorithm_id(&private_key_info.algorithm)?;
|
||||
RsaPrivateKey::try_from(private_key_info).map(Self::new)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> ZeroizeOnDrop for SigningKey<D> where D: Digest {}
|
||||
|
||||
impl<D> PartialEq for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inner == other.inner && self.salt_len == other.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<D> Serialize for SigningKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serdect::serde::Serializer,
|
||||
{
|
||||
let der = self.to_pkcs8_der().map_err(ser::Error::custom)?;
|
||||
serdect::slice::serialize_hex_lower_or_bin(&der.as_bytes(), serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, D> Deserialize<'de> for SigningKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
fn deserialize<De>(deserializer: De) -> core::result::Result<Self, De::Error>
|
||||
where
|
||||
De: serdect::serde::Deserializer<'de>,
|
||||
{
|
||||
let der_bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
|
||||
Self::from_pkcs8_der(&der_bytes).map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
#[cfg(all(feature = "hazmat", feature = "serde"))]
|
||||
fn test_serde() {
|
||||
use super::*;
|
||||
use crate::RsaPrivateKey;
|
||||
use rand::rngs::ChaCha8Rng;
|
||||
use rand_core::SeedableRng;
|
||||
use serde_test::{assert_tokens, Configure, Token};
|
||||
use sha2::Sha256;
|
||||
|
||||
let mut rng = ChaCha8Rng::from_seed([42; 32]);
|
||||
let priv_key = RsaPrivateKey::new_unchecked(&mut rng, 64).expect("failed to generate key");
|
||||
let signing_key = SigningKey::<Sha256>::new(priv_key);
|
||||
|
||||
let tokens = [Token::Str(concat!(
|
||||
"3056020100300d06092a864886f70d010101050004423040020100020900ab240c",
|
||||
"3361d02e370203010001020811e54a15259d22f9020500ceff5cf3020500d3a7aa",
|
||||
"ad020500ccaddf17020500cb529d3d020500bb526d6f"
|
||||
))];
|
||||
|
||||
assert_tokens(&signing_key.readable(), &tokens);
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
use super::{verify_digest, Signature};
|
||||
use crate::RsaPublicKey;
|
||||
use core::marker::PhantomData;
|
||||
use digest::{Digest, FixedOutputReset, Update};
|
||||
use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
use {
|
||||
crate::encoding::ID_RSASSA_PSS,
|
||||
const_oid::AssociatedOid,
|
||||
pkcs8::{Document, EncodePublicKey},
|
||||
spki::{der::AnyRef, AlgorithmIdentifierRef, AssociatedAlgorithmIdentifier},
|
||||
};
|
||||
#[cfg(feature = "serde")]
|
||||
use {
|
||||
serdect::serde::{de, ser, Deserialize, Serialize},
|
||||
spki::DecodePublicKey,
|
||||
};
|
||||
|
||||
/// Verifying key for checking the validity of RSASSA-PSS signatures as
|
||||
/// described in [RFC8017 § 8.1].
|
||||
///
|
||||
/// [RFC8017 § 8.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.1
|
||||
#[derive(Debug)]
|
||||
pub struct VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
pub(super) inner: RsaPublicKey,
|
||||
pub(super) salt_len: Option<usize>,
|
||||
pub(super) phantom: PhantomData<D>,
|
||||
}
|
||||
|
||||
impl<D> VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
/// Create a new RSASSA-PSS verifying key.
|
||||
/// Digest output size is used as a salt length.
|
||||
pub fn new(key: RsaPublicKey) -> Self {
|
||||
Self::new_with_salt_len(key, <D as Digest>::output_size())
|
||||
}
|
||||
|
||||
/// Create a new RSASSA-PSS verifying key.
|
||||
pub fn new_with_salt_len(key: RsaPublicKey, salt_len: usize) -> Self {
|
||||
Self {
|
||||
inner: key,
|
||||
salt_len: Some(salt_len),
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new RSASSA-PSS verifying key.
|
||||
/// Attempts to automatically detect the salt length.
|
||||
pub fn new_with_auto_salt_len(key: RsaPublicKey) -> Self {
|
||||
Self {
|
||||
inner: key,
|
||||
salt_len: None,
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return specified salt length for this key
|
||||
pub fn salt_len(&self) -> Option<usize> {
|
||||
self.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// `*Verifier` trait impls
|
||||
//
|
||||
|
||||
impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset + Update,
|
||||
{
|
||||
fn verify_digest<F: Fn(&mut D) -> signature::Result<()>>(
|
||||
&self,
|
||||
f: F,
|
||||
signature: &Signature,
|
||||
) -> signature::Result<()> {
|
||||
let mut digest = D::new();
|
||||
f(&mut digest)?;
|
||||
verify_digest::<D>(
|
||||
&self.inner,
|
||||
&digest.finalize(),
|
||||
&signature.inner,
|
||||
self.salt_len,
|
||||
)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
|
||||
verify_digest::<D>(&self.inner, prehash, &signature.inner, self.salt_len)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> Verifier<Signature> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest + FixedOutputReset,
|
||||
{
|
||||
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
|
||||
verify_digest::<D>(
|
||||
&self.inner,
|
||||
&D::digest(msg),
|
||||
&signature.inner,
|
||||
self.salt_len,
|
||||
)
|
||||
.map_err(|e| e.into())
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Other trait impls
|
||||
//
|
||||
|
||||
impl<D> AsRef<RsaPublicKey> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn as_ref(&self) -> &RsaPublicKey {
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> AssociatedAlgorithmIdentifier for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
type Params = AnyRef<'static>;
|
||||
|
||||
const ALGORITHM_IDENTIFIER: AlgorithmIdentifierRef<'static> = pkcs1::ALGORITHM_ID;
|
||||
}
|
||||
|
||||
// Implemented manually so we don't have to bind D with Clone
|
||||
impl<D> Clone for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.clone(),
|
||||
salt_len: self.salt_len,
|
||||
phantom: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> EncodePublicKey for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn to_public_key_der(&self) -> spki::Result<Document> {
|
||||
self.inner.to_public_key_der()
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<RsaPublicKey> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: RsaPublicKey) -> Self {
|
||||
Self::new(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> From<VerifyingKey<D>> for RsaPublicKey
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn from(key: VerifyingKey<D>) -> Self {
|
||||
key.inner
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "encoding")]
|
||||
impl<D> TryFrom<pkcs8::SubjectPublicKeyInfoRef<'_>> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
type Error = spki::Error;
|
||||
|
||||
fn try_from(spki: pkcs8::SubjectPublicKeyInfoRef<'_>) -> spki::Result<Self> {
|
||||
match spki.algorithm.oid {
|
||||
ID_RSASSA_PSS | pkcs1::ALGORITHM_OID => (),
|
||||
_ => {
|
||||
return Err(spki::Error::OidUnknown {
|
||||
oid: spki.algorithm.oid,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
RsaPublicKey::try_from(spki).map(Self::new)
|
||||
}
|
||||
}
|
||||
|
||||
impl<D> PartialEq for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inner == other.inner && self.salt_len == other.salt_len
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<D> Serialize for VerifyingKey<D>
|
||||
where
|
||||
D: Digest,
|
||||
{
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
let der = self.to_public_key_der().map_err(ser::Error::custom)?;
|
||||
serdect::slice::serialize_hex_lower_or_bin(&der, serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
impl<'de, D> Deserialize<'de> for VerifyingKey<D>
|
||||
where
|
||||
D: Digest + AssociatedOid,
|
||||
{
|
||||
fn deserialize<De>(deserializer: De) -> Result<Self, De::Error>
|
||||
where
|
||||
De: serde::Deserializer<'de>,
|
||||
{
|
||||
let der_bytes = serdect::slice::deserialize_hex_or_bin_vec(deserializer)?;
|
||||
Self::from_public_key_der(&der_bytes).map_err(de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
#[cfg(all(feature = "hazmat", feature = "serde"))]
|
||||
fn test_serde() {
|
||||
use super::*;
|
||||
use crate::RsaPrivateKey;
|
||||
use rand::rngs::ChaCha8Rng;
|
||||
use rand_core::SeedableRng;
|
||||
use serde_test::{assert_tokens, Configure, Token};
|
||||
use sha2::Sha256;
|
||||
|
||||
let mut rng = ChaCha8Rng::from_seed([42; 32]);
|
||||
let priv_key = RsaPrivateKey::new_unchecked(&mut rng, 64).expect("failed to generate key");
|
||||
let pub_key = priv_key.to_public_key();
|
||||
let verifying_key = VerifyingKey::<Sha256>::new(pub_key);
|
||||
|
||||
let tokens = [Token::Str(
|
||||
"3024300d06092a864886f70d01010105000313003010020900ab240c3361d02e370203010001",
|
||||
)];
|
||||
|
||||
assert_tokens(&verifying_key.readable(), &tokens);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user