Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,7 +19,7 @@ subtle = { version = "2.6.1", default-features = false }
digest = { version = "=0.11.0-pre.10", default-features = false, features = ["alloc", "oid"] }
pkcs1 = { version = "0.8.0-rc.1", default-features = false, features = ["alloc", "pkcs8"] }
pkcs8 = { version = "0.11.0-rc.2", default-features = false, features = ["alloc"] }
signature = { version = "=2.3.0-pre.6", default-features = false, features = ["alloc", "digest", "rand_core"] }
signature = { version = "=3.0.0-pre", default-features = false, features = ["alloc", "digest", "rand_core"] }
spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"] }
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.7.0-pre", default-features = false, features = ["zeroize", "alloc"] }
Expand DownExpand Up@@ -57,7 +57,7 @@ os_rng = ["rand_core/os_rng", "crypto-bigint/rand_core"]
serde = ["dep:serde", "dep:serdect", "crypto-bigint/serde"]
pem = ["pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "signature/std", "crypto-bigint/rand"]
std = ["digest/std", "pkcs1/std", "pkcs8/std", "rand_core/std", "crypto-bigint/rand"]


[package.metadata.docs.rs]
Expand Down
68 changes: 54 additions & 14 deletions src/pkcs1v15/signature.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,16 @@

use ::signature::SignatureEncoding;
use alloc::boxed::Box;
use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
use core::{
fmt::{self, Debug, Display, Formatter, LowerHex, UpperHex},
marker::PhantomData,
};
use crypto_bigint::BoxedUint;

use digest::Digest;
#[cfg(feature = "serde")]
use serdect::serde::{de, Deserialize, Serialize};
use signature::PrehashSignature;
use spki::{
der::{asn1::BitString, Result as DerResult},
SignatureBitStringEncoding,
Expand All@@ -15,22 +20,46 @@ use spki::{
/// `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
///
/// [RFC8017 § 8.2]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.2
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signature {
#[derive(Eq)]
pub struct Signature<D> {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This still seems a little weird to me because there isn't a strong binding or relationship between the signature as a cryptographic object and the digest algorithm that was used to compute it.

This means that the type does not actually maintain an invariant e.g. "this is a signature that was known to be computed by using digest D over the input message". It could've been computed with any digest algorithm.

I guess there's a type safety argument to it in that the type identifies what digest you're supposed to use, but as cryptographic objects they're not really parameterized/distinguished by the digest, it's just something that happens earlier in the computation of the signature.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@baloo WDYT?

Copy link
Copy Markdown
MemberAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don’t know what I think ^^.
I know that I don’t really have much of a choice.

What I’m arguing it that it makes the digest explicit when accepting/parsing a signature: “I know this is going to be verified with this public key with sha384”

I know the serialization does not necessarily carry this information, although it would be carried via the OID on the object (x509 or cms) or via a specification or however the developer may which. Whichever that might be the digest will need to be provided for the VerifyingKey.

all in all this is a little bit inconvenient, but not all that much and it just makes the digest choice explicit.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the only reason it exists is for the PrehashSignature impl.

I find it a little troubling it otherwise doesn't actually do anything, but I guess we need to merge this to make any progress.

pub(super) inner: BoxedUint,
_digest: PhantomData<D>,
}

impl<D> Debug for Signature<D> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Signature")
.field("inner", &self.inner)
.finish()
}
}

impl SignatureEncoding for Signature {
impl<D> Clone for Signature<D> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
_digest: PhantomData,
}
}
}

impl<D> PartialEq for Signature<D> {
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}

impl<D> SignatureEncoding for Signature<D> {
type Repr = Box<[u8]>;
}

impl SignatureBitStringEncoding for Signature {
impl<D> SignatureBitStringEncoding for Signature<D> {
fn to_bitstring(&self) -> DerResult<BitString> {
BitString::new(0, self.to_vec())
}
}

impl TryFrom<&[u8]> for Signature {
impl<D> TryFrom<&[u8]> for Signature<D> {
type Error = signature::Error;

fn try_from(bytes: &[u8]) -> signature::Result<Self> {
Expand All@@ -42,17 +71,20 @@ impl TryFrom<&[u8]> for Signature {
#[cfg(not(feature = "std"))]
let inner = inner.map_err(|_| signature::Error::new())?;

Ok(Self { inner })
Ok(Self {
inner,
_digest: PhantomData,
})
}
}

impl From<Signature> for Box<[u8]> {
fn from(signature: Signature) -> Box<[u8]> {
impl<D> From<Signature<D>> for Box<[u8]> {
fn from(signature: Signature<D>) -> Box<[u8]> {
signature.inner.to_be_bytes()
}
}

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

impl UpperHex for Signature {
impl<D> UpperHex for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
for byte in self.to_bytes().iter() {
write!(f, "{:02X}", byte)?;
Expand All@@ -70,14 +102,14 @@ impl UpperHex for Signature {
}
}

impl Display for Signature {
impl<D> Display for Signature<D> {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "{:X}", self)
}
}

#[cfg(feature = "serde")]
impl Serialize for Signature {
impl<D> Serialize for Signature<D> {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serdect::serde::Serializer,
Expand All@@ -87,7 +119,7 @@ impl Serialize for Signature {
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Signature {
impl<'de, Di> Deserialize<'de> for Signature<Di> {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serdect::serde::Deserializer<'de>,
Expand All@@ -99,6 +131,13 @@ impl<'de> Deserialize<'de> for Signature {
}
}

impl<D> PrehashSignature for Signature<D>
where
D: Digest,
{
type Digest = D;
}

#[cfg(test)]
mod tests {
#[test]
Expand All@@ -108,6 +147,7 @@ mod tests {
use serde_test::{assert_tokens, Configure, Token};
let signature = Signature {
inner: BoxedUint::from(42u32),
_digest: PhantomData::<()>,
};

let tokens = [Token::Str("000000000000002a")];
Expand Down
42 changes: 7 additions & 35 deletions src/pkcs1v15/signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,9 +17,7 @@ use {
serdect::serde::{de, ser, Deserialize, Serialize},
};

use signature::{
hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner, RandomizedSigner, Signer,
};
use signature::{hazmat::PrehashSigner, DigestSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;

/// Signing key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -101,69 +99,43 @@ where
// `*Signer` trait impls
//

impl<D> DigestSigner<D, Signature> for SigningKey<D>
impl<D> DigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature> {
fn try_sign_digest(&self, digest: D) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> PrehashSigner<Signature> for SigningKey<D>
impl<D> PrehashSigner<Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature> {
fn sign_prehash(&self, prehash: &[u8]) -> signature::Result<Signature<D>> {
sign::<DummyRng>(None, &self.inner, &self.prefix, prehash)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for SigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for SigningKey<D>
where
D: Digest,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign(Some(rng), &self.inner, &self.prefix, &digest.finalize())?
.as_slice()
.try_into()
}
}

impl<D> RandomizedSigner<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
msg: &[u8],
) -> signature::Result<Signature> {
sign(Some(rng), &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

impl<D> Signer<Signature> for SigningKey<D>
where
D: Digest,
{
fn try_sign(&self, msg: &[u8]) -> signature::Result<Signature> {
sign::<DummyRng>(None, &self.inner, &self.prefix, &D::digest(msg))?
.as_slice()
.try_into()
}
}

//
// Other trait impls
//
Expand Down
25 changes: 5 additions & 20 deletions src/pkcs1v15/verifying_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -17,7 +17,7 @@ use {
spki::DecodePublicKey,
};

use signature::{hazmat::PrehashVerifier, DigestVerifier, Verifier};
use signature::{hazmat::PrehashVerifier, DigestVerifier};
use spki::{Document, EncodePublicKey};

/// Verifying key for `RSASSA-PKCS1-v1_5` signatures as described in [RFC8017 § 8.2].
Expand DownExpand Up@@ -75,11 +75,11 @@ where
// `*Verifier` trait impls
//

impl<D> DigestVerifier<D, Signature> for VerifyingKey<D>
impl<D> DigestVerifier<D, Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_digest(&self, digest: D, signature: &Signature) -> signature::Result<()> {
fn verify_digest(&self, digest: D, signature: &Signature<D>) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix,
Expand All@@ -90,30 +90,15 @@ where
}
}

impl<D> PrehashVerifier<Signature> for VerifyingKey<D>
impl<D> PrehashVerifier<Signature<D>> for VerifyingKey<D>
where
D: Digest,
{
fn verify_prehash(&self, prehash: &[u8], signature: &Signature) -> signature::Result<()> {
fn verify_prehash(&self, prehash: &[u8], signature: &Signature<D>) -> signature::Result<()> {
verify(&self.inner, &self.prefix, prehash, &signature.inner).map_err(|e| e.into())
}
}

impl<D> Verifier<Signature> for VerifyingKey<D>
where
D: Digest,
{
fn verify(&self, msg: &[u8], signature: &Signature) -> signature::Result<()> {
verify(
&self.inner,
&self.prefix.clone(),
&D::digest(msg),
&signature.inner,
)
.map_err(|e| e.into())
}
}

//
// Other trait impls
//
Expand Down
27 changes: 5 additions & 22 deletions src/pss/blinded_signing_key.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -11,9 +11,7 @@ use pkcs8::{
EncodePrivateKey, SecretDocument,
};
use rand_core::{CryptoRng, TryCryptoRng};
use signature::{
hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner, RandomizedSigner,
};
use signature::{hazmat::RandomizedPrehashSigner, Keypair, RandomizedDigestSigner};
use zeroize::ZeroizeOnDrop;
#[cfg(feature = "serde")]
use {
Expand DownExpand Up@@ -84,45 +82,30 @@ where
// `*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> {
sign_digest::<_, D>(rng, true, &self.inner, &D::digest(msg), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedDigestSigner<D, Signature> for BlindedSigningKey<D>
impl<D> RandomizedDigestSigner<D, Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn try_sign_digest_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
digest: D,
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, &digest.finalize(), self.salt_len)?
.as_slice()
.try_into()
}
}

impl<D> RandomizedPrehashSigner<Signature> for BlindedSigningKey<D>
impl<D> RandomizedPrehashSigner<Signature<D>> for BlindedSigningKey<D>
where
D: Digest + FixedOutputReset,
{
fn sign_prehash_with_rng<R: TryCryptoRng + ?Sized>(
&self,
rng: &mut R,
prehash: &[u8],
) -> signature::Result<Signature> {
) -> signature::Result<Signature<D>> {
sign_digest::<_, D>(rng, true, &self.inner, prehash, self.salt_len)?
.as_slice()
.try_into()
Expand Down
Loading