Skip to content

Commit

Permalink
feat: switch to version 2.0 (pre) of the signature crate
Browse files Browse the repository at this point in the history
Rework the crate to implement traits from the preview of the signature
crate. Use Vec<u8> as Self::Repr type.

Signed-off-by: Dmitry Baryshkov <[email protected]>
  • Loading branch information
lumag committed Oct 31, 2022
1 parent a857c8f commit 84fcd86
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 97 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ subtle = { version = "2.1.1", default-features = false }
digest = { version = "0.10.5", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.4", default-features = false, features = ["pkcs8", "alloc"] }
pkcs8 = { version = "0.9", default-features = false, features = ["alloc"] }
signature = { version = "1.6.4", default-features = false , features = ["digest-preview", "rand-preview"] }
signature = { version = "2.0.0-pre", default-features = false , features = ["digest-preview", "rand-preview"] }
zeroize = { version = "1", features = ["alloc"] }

# Temporary workaround until https://github.com/dignifiedquire/num-bigint/pull/42 lands
Expand Down Expand Up @@ -53,7 +53,7 @@ name = "key"

[features]
default = ["std", "pem"]
hazmat = ["signature/hazmat-preview"]
hazmat = []
nightly = ["num-bigint/nightly"]
serde = ["num-bigint/serde", "serde_crate"]
expose-internals = []
Expand Down
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
//! use rsa::RsaPrivateKey;
//! use rsa::pkcs1v15::{SigningKey, VerifyingKey};
//! use sha2::{Digest, Sha256};
//! use signature::{RandomizedSigner, Signature, Verifier};
//! use signature::{RandomizedSigner, SignatureEncoding, Verifier};
//!
//! let mut rng = rand::thread_rng();
//!
Expand All @@ -64,7 +64,7 @@
//! // Sign
//! let data = b"hello world";
//! let signature = signing_key.sign_with_rng(&mut rng, data);
//! assert_ne!(signature.as_bytes(), data);
//! assert_ne!(signature.to_bytes().as_ref(), data.as_slice());
//!
//! // Verify
//! verifying_key.verify(data, &signature).expect("failed to verify");
Expand All @@ -75,7 +75,7 @@
//! use rsa::RsaPrivateKey;
//! use rsa::pss::{BlindedSigningKey, VerifyingKey};
//! use sha2::{Digest, Sha256};
//! use signature::{RandomizedSigner, Signature, Verifier};
//! use signature::{RandomizedSigner, SignatureEncoding, Verifier};
//!
//! let mut rng = rand::thread_rng();
//!
Expand All @@ -87,7 +87,7 @@
//! // Sign
//! let data = b"hello world";
//! let signature = signing_key.sign_with_rng(&mut rng, data);
//! assert_ne!(signature.as_bytes(), data);
//! assert_ne!(signature.to_bytes().as_ref(), data);
//!
//! // Verify
//! verifying_key.verify(data, &signature).expect("failed to verify");
Expand Down
84 changes: 39 additions & 45 deletions src/pkcs1v15.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
use alloc::vec;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::marker::PhantomData;
use core::ops::Deref;
use digest::Digest;
use pkcs8::{AssociatedOid, Document, EncodePrivateKey, EncodePublicKey, SecretDocument};
use rand_core::{CryptoRng, RngCore};
#[cfg(feature = "hazmat")]
use signature::hazmat::{PrehashSigner, PrehashVerifier};
use signature::{
DigestSigner, DigestVerifier, RandomizedDigestSigner, RandomizedSigner,
Signature as SignSignature, Signer, Verifier,
DigestSigner, DigestVerifier, RandomizedDigestSigner, RandomizedSigner, SignatureEncoding,
Signer, Verifier,
};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroizing;
Expand All @@ -20,60 +19,52 @@ use crate::errors::{Error, Result};
use crate::key::{self, PrivateKey, PublicKey};
use crate::{RsaPrivateKey, RsaPublicKey};

#[derive(Clone)]
#[derive(Clone, PartialEq, Eq)]
pub struct Signature {
bytes: Vec<u8>,
bytes: Box<[u8]>,
}

impl signature::Signature for Signature {
fn from_bytes(bytes: &[u8]) -> signature::Result<Self> {
Ok(Signature {
bytes: bytes.into(),
})
}

fn as_bytes(&self) -> &[u8] {
self.bytes.as_slice()
}
impl SignatureEncoding for Signature {
type Repr = Box<[u8]>;
}

impl From<Vec<u8>> for Signature {
fn from(bytes: Vec<u8>) -> Self {
impl From<Box<[u8]>> for Signature {
fn from(bytes: Box<[u8]>) -> Self {
Self { bytes }
}
}

impl Deref for Signature {
type Target = [u8];
impl<'a> TryFrom<&'a [u8]> for Signature {
type Error = signature::Error;

fn deref(&self) -> &Self::Target {
self.as_bytes()
fn try_from(bytes: &'a [u8]) -> signature::Result<Self> {
Ok(Self {
bytes: bytes.into(),
})
}
}

impl PartialEq for Signature {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
signature.bytes
}
}

impl Eq for Signature {}

impl Debug for Signature {
fn fmt(&self, fmt: &mut Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
fmt.debug_list().entries(self.as_bytes().iter()).finish()
impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
self.bytes.as_ref()
}
}

impl AsRef<[u8]> for Signature {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
impl Debug for Signature {
fn fmt(&self, fmt: &mut Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
fmt.debug_list().entries(self.bytes.iter()).finish()
}
}

impl LowerHex for Signature {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.as_bytes() {
for byte in self.bytes.iter() {
write!(f, "{:02x}", byte)?;
}
Ok(())
Expand All @@ -82,7 +73,7 @@ impl LowerHex for Signature {

impl UpperHex for Signature {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.as_bytes() {
for byte in self.bytes.iter() {
write!(f, "{:02X}", byte)?;
}
Ok(())
Expand Down Expand Up @@ -391,7 +382,7 @@ where
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng, _>(None, &self.inner, &self.prefix, &D::digest(msg))
.map(|v| v.into())
.map(|v| v.into_boxed_slice().into())
.map_err(|e| e.into())
}
}
Expand All @@ -406,7 +397,7 @@ where
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(&mut rng), &self.inner, &self.prefix, &D::digest(msg))
.map(|v| v.into())
.map(|v| v.into_boxed_slice().into())
.map_err(|e| e.into())
}
}
Expand All @@ -417,7 +408,7 @@ where
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
sign::<DummyRng, _>(None, &self.inner, &self.prefix, &digest.finalize())
.map(|v| v.into())
.map(|v| v.into_boxed_slice().into())
.map_err(|e| e.into())
}
}
Expand All @@ -437,7 +428,7 @@ where
&self.prefix,
&digest.finalize(),
)
.map(|v| v.into())
.map(|v| v.into_boxed_slice().into())
.map_err(|e| e.into())
}
}
Expand All @@ -449,7 +440,7 @@ where
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng, _>(None, &self.inner, &self.prefix, prehash)
.map(|v| v.into())
.map(|v| v.into_boxed_slice().into())
.map_err(|e| e.into())
}
}
Expand Down Expand Up @@ -604,7 +595,7 @@ mod tests {
use sha1::{Digest, Sha1};
use sha2::Sha256;
use sha3::Sha3_256;
use signature::{RandomizedSigner, Signature, Signer, Verifier};
use signature::{RandomizedSigner, Signer, Verifier};

use crate::{PaddingScheme, PublicKey, PublicKeyParts, RsaPrivateKey, RsaPublicKey};

Expand Down Expand Up @@ -898,8 +889,10 @@ mod tests {
let verifying_key = VerifyingKey::<Sha1>::new_with_prefix(pub_key);

for (text, sig, expected) in &tests {
let result =
verifying_key.verify(text.as_bytes(), &Signature::from_bytes(sig).unwrap());
let result = verifying_key.verify(
text.as_bytes(),
&Signature::try_from(sig.as_slice()).unwrap(),
);
match expected {
true => result.expect("failed to verify"),
false => {
Expand Down Expand Up @@ -937,7 +930,8 @@ mod tests {
for (text, sig, expected) in &tests {
let mut digest = Sha1::new();
digest.update(text.as_bytes());
let result = verifying_key.verify_digest(digest, &Signature::from_bytes(sig).unwrap());
let result =
verifying_key.verify_digest(digest, &Signature::try_from(sig.as_slice()).unwrap());
match expected {
true => result.expect("failed to verify"),
false => {
Expand Down Expand Up @@ -976,7 +970,7 @@ mod tests {

let verifying_key: VerifyingKey<_> = (&signing_key).into();
verifying_key
.verify_prehash(msg, &Signature::from_bytes(&expected_sig).unwrap())
.verify_prehash(msg, &Signature::from_bytes(&expected_sig.into_boxed_slice()).unwrap())
.expect("failed to verify");
}
}
Loading

0 comments on commit 84fcd86

Please sign in to comment.