use crate::{CryptoError, HashAlgorithm, SignatureScheme};
use num_bigint::BigUint;
use subtle::ConstantTimeEq;
const MIN_MODULUS_BITS: u64 = 1024;
const MAX_MODULUS_BITS: u64 = 8192;
fn digest_info_without_parameters(
scheme: SignatureScheme,
) -> Option<(HashAlgorithm, &'static [u8])> {
Some(match scheme {
SignatureScheme::RsaPkcs1Sha1 => (
HashAlgorithm::Sha1,
&[
0x30, 0x1f, 0x30, 0x07, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x04, 0x14,
],
),
SignatureScheme::RsaPkcs1Sha256 => (
HashAlgorithm::Sha256,
&[
0x30, 0x2f, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x01, 0x04, 0x20,
],
),
SignatureScheme::RsaPkcs1Sha384 => (
HashAlgorithm::Sha384,
&[
0x30, 0x3f, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x02, 0x04, 0x30,
],
),
SignatureScheme::RsaPkcs1Sha512 => (
HashAlgorithm::Sha512,
&[
0x30, 0x4f, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02,
0x03, 0x04, 0x40,
],
),
_ => return None,
})
}
pub fn rsa_pkcs1_hash(scheme: SignatureScheme) -> Option<HashAlgorithm> {
digest_info_without_parameters(scheme).map(|(hash, _)| hash)
}
fn der_tlv(input: &[u8], tag: u8) -> Result<(&[u8], &[u8]), CryptoError> {
let bad = || CryptoError::InvalidPublicKey;
let (&t, rest) = input.split_first().ok_or_else(bad)?;
if t != tag {
return Err(bad());
}
let (&first, mut rest) = rest.split_first().ok_or_else(bad)?;
let len = match first {
0..=0x7f => first as usize,
0x81 => {
let (&b, r) = rest.split_first().ok_or_else(bad)?;
rest = r;
if b < 0x80 {
return Err(bad());
}
b as usize
}
0x82 => {
if rest.len() < 2 || rest[0] == 0 {
return Err(bad());
}
let len = u16::from_be_bytes([rest[0], rest[1]]) as usize;
rest = &rest[2..];
if len < 0x100 {
return Err(bad());
}
len
}
_ => return Err(bad()),
};
if rest.len() < len {
return Err(bad());
}
Ok((&rest[..len], &rest[len..]))
}
fn der_positive_integer(input: &[u8]) -> Result<(BigUint, &[u8]), CryptoError> {
let (contents, rest) = der_tlv(input, 0x02)?;
let magnitude = match contents {
[] => return Err(CryptoError::InvalidPublicKey),
[0, next, ..] if *next >= 0x80 => &contents[1..],
[0, _, ..] => return Err(CryptoError::InvalidPublicKey),
[first, ..] if *first >= 0x80 => return Err(CryptoError::InvalidPublicKey),
_ => contents,
};
Ok((BigUint::from_bytes_be(magnitude), rest))
}
fn rsa_public_key(der: &[u8]) -> Result<(BigUint, BigUint), CryptoError> {
let (sequence, trailing) = der_tlv(der, 0x30)?;
if !trailing.is_empty() {
return Err(CryptoError::InvalidPublicKey);
}
let (n, rest) = der_positive_integer(sequence)?;
let (e, rest) = der_positive_integer(rest)?;
if !rest.is_empty() {
return Err(CryptoError::InvalidPublicKey);
}
Ok((n, e))
}
pub fn verify_rsa_pkcs1_without_digest_parameters(
scheme: SignatureScheme,
public_key: &[u8],
digest: &[u8],
signature: &[u8],
) -> Result<(), CryptoError> {
let (hash, prefix) =
digest_info_without_parameters(scheme).ok_or(CryptoError::InvalidSignature)?;
if digest.len() != hash.output_len() {
return Err(CryptoError::InvalidSignature);
}
let (n, e) = rsa_public_key(public_key)?;
let bits = n.bits();
if !(MIN_MODULUS_BITS..=MAX_MODULUS_BITS).contains(&bits) || e < BigUint::from(3u8) || !e.bit(0)
{
return Err(CryptoError::InvalidPublicKey);
}
let k = bits.div_ceil(8) as usize;
if signature.len() != k {
return Err(CryptoError::InvalidSignature);
}
let s = BigUint::from_bytes_be(signature);
if s >= n {
return Err(CryptoError::InvalidSignature);
}
let m = s.modpow(&e, &n).to_bytes_be();
let mut em = vec![0u8; k - m.len()];
em.extend_from_slice(&m);
let t_len = prefix.len() + digest.len();
if k < t_len + 11 {
return Err(CryptoError::InvalidSignature);
}
let mut expected = Vec::with_capacity(k);
expected.extend_from_slice(&[0x00, 0x01]);
expected.resize(k - t_len - 1, 0xff);
expected.push(0x00);
expected.extend_from_slice(prefix);
expected.extend_from_slice(digest);
if bool::from(em.ct_eq(&expected)) {
Ok(())
} else {
Err(CryptoError::InvalidSignature)
}
}