sign: delegate BER and DER encoding to existing craft-pkcs7

This commit is contained in:
Dylan M. Taylor committed 2026-11-15 09:35:45 -05:00
1 parent e098c5c85e
commit bb158c0ab8
4 files changed
+124 -535

No files matched your search

Generated
+38 -5
View File
@@ -1327,6 +1327,38 @@ dependencies = [
"zeroize",
]
[[package]]
name = "craft-pkcs7"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f#2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f"
dependencies = [
"aes",
"aws-lc-rs",
"base64 0.23.1",
"bp256",
"bp384",
"cbc",
"chrono",
"crypto-bigint",
"des",
"ecdsa",
"ed25519-dalek",
"getrandom 0.4.3",
"hmac",
"p256",
"p384",
"p521",
"pbkdf2",
"rc2",
"ripemd",
"rsa",
"sha1 0.11.0",
"sha2 0.11.1",
"sha3",
"thiserror 2.0.21",
"zeroize",
]
[[package]]
name = "craft-prc"
version = "0.1.0"
@@ -1548,9 +1580,9 @@ checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-bigint"
version = "0.7.6"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb08299a6046833a879ace115697f12fd2bd6c8d3e93c909ffc9e0738e7cae0"
checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
dependencies = [
"cpubits",
"ctutils",
@@ -1596,9 +1628,9 @@ dependencies = [
[[package]]
name = "ctutils"
version = "0.4.5"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d28fb6aa7dd680b3ffd1a3e64e115c177bdba63c0ae7f9cd48129ff05c4fa0"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
"subtle",
@@ -4934,6 +4966,7 @@ dependencies = [
"bp384",
"cbc",
"chrono",
"craft-pkcs7",
"crypto-bigint",
"des",
"ecdsa",
@@ -7136,7 +7169,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom 0.4.3",
"getrandom 0.3.4",
"once_cell",
"rustix 1.1.6",
"windows-sys 0.61.2",
+2
View File
@@ -11,6 +11,8 @@ repository.workspace = true
workspace = true
[dependencies]
# Existing shared ASN.1 codec; PDF signature policy remains local.
craft-pkcs7 = { git = "https://github.com/storytold/craft-libs", rev = "2284a6bf76b3d629b5e5bb2ca71e1c319d8dae5f" }
pdfcraft-cos = { workspace = true }
pdfcraft-annot = { workspace = true }
pdfcraft-content = { workspace = true }
+83 -529
View File
@@ -1,564 +1,118 @@
//! A small BER/DER reader and writer (ITU-T X.690): just what X.509, CMS and PKCS#12 need.
//! BER/DER codecs delegated to the existing shared `craft-pkcs7` implementation.
//!
//! [`Tlv`] borrows from the input and keeps its full encoding (`raw`), so signed structures can
//! be verified over the exact bytes that were signed.
//!
//! Reading is strict DER by default, which is what everything signed must use. [`Tlv::parse_ber`]
//! also accepts the two BER constructions a reader meets in practice — the indefinite length form
//! and strings split into segments — which PKCS #12 needs: Windows writes `.p12` files that way.
//! Writing is always DER.
use std::borrow::Cow;
//! This facade preserves PdfCraft's error type and borrowed signed encodings. Certificate
//! trust, signing policy and document interpretation remain in their existing app modules.
use crate::SignError;
use craft_pkcs7::der as shared;
pub use shared::{Form, Time, algorithm, bit_string, boolean, explicit, ia5, int, null, octets, oid, printable, seq, set_of, tag, tlv, uint, utf8};
use std::borrow::Cow;
/// Universal tags (single-byte identifiers).
pub mod tag {
pub const BOOLEAN: u8 = 0x01;
pub const INTEGER: u8 = 0x02;
pub const ENUMERATED: u8 = 0x0A;
pub const BIT_STRING: u8 = 0x03;
pub const OCTET_STRING: u8 = 0x04;
/// An OCTET STRING split into segments (BER only, X.690 §8.21); see [`super::Tlv::octets`].
pub const OCTET_STRING_SEGMENTS: u8 = 0x24;
pub const NULL: u8 = 0x05;
pub const OID: u8 = 0x06;
pub const UTF8_STRING: u8 = 0x0C;
pub const PRINTABLE_STRING: u8 = 0x13;
pub const T61_STRING: u8 = 0x14;
pub const IA5_STRING: u8 = 0x16;
pub const UTC_TIME: u8 = 0x17;
pub const GENERALIZED_TIME: u8 = 0x18;
pub const BMP_STRING: u8 = 0x1E;
pub const SEQUENCE: u8 = 0x30;
pub const SET: u8 = 0x31;
/// `[n]` context-specific, constructed (EXPLICIT, or IMPLICIT over a constructed type).
pub const fn ctx(n: u8) -> u8 {
0xA0 | n
}
/// `[n]` context-specific, primitive (IMPLICIT over a primitive type).
pub const fn ctx_prim(n: u8) -> u8 {
0x80 | n
fn app_error(error: craft_pkcs7::Error) -> SignError {
match error {
craft_pkcs7::Error::Malformed(message) => SignError::Malformed(message),
craft_pkcs7::Error::Unsupported(message) => SignError::Unsupported(message),
craft_pkcs7::Error::WrongPassword => SignError::WrongPassword,
craft_pkcs7::Error::Crypto(message) => SignError::Crypto(message),
}
}
fn bad(what: &str) -> SignError {
SignError::Malformed(what.to_string())
}
/// Which encoding rules a reader accepts.
/// A borrowed shared element with the app's existing fallible method signatures.
/// Dereferencing exposes the same public tag, contents and exact original encoding.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Form {
/// DER: every length definite, every string primitive. Anything whose bytes are signed is read
/// this way, so that what is verified is exactly what was written.
Der,
/// BER as well: the indefinite length form (X.690 §8.1.3.6) and strings split into segments
/// (§8.21).
Ber,
pub struct Tlv<'a>(shared::Tlv<'a>);
impl<'a> std::ops::Deref for Tlv<'a> {
type Target = shared::Tlv<'a>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
/// One BER/DER element.
#[derive(Clone, Copy, Debug, Eq)]
pub struct Tlv<'a> {
pub tag: u8,
/// The contents octets (without the end-of-contents octets of an indefinite length).
pub value: &'a [u8],
/// The whole encoding (identifier, length, contents and any end-of-contents octets).
pub raw: &'a [u8],
/// The rules this element was read with. Its children are read the same way.
form: Form,
}
/// Two elements are equal when they encode the same thing; the rules they were read with are not
/// part of that.
impl PartialEq for Tlv<'_> {
fn eq(&self, other: &Self) -> bool {
self.tag == other.tag && self.value == other.value && self.raw == other.raw
impl std::ops::DerefMut for Tlv<'_> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<'a> Tlv<'a> {
/// Parse one DER element at the start of `input`; returns it and the rest.
pub fn parse(input: &'a [u8]) -> Result<(Tlv<'a>, &'a [u8]), SignError> {
Tlv::read(input, Form::Der, 0)
}
/// Parse one BER element at the start of `input`; returns it and the rest.
pub fn parse_ber(input: &'a [u8]) -> Result<(Tlv<'a>, &'a [u8]), SignError> {
Tlv::read(input, Form::Ber, 0)
}
fn read(input: &'a [u8], form: Form, depth: usize) -> Result<(Tlv<'a>, &'a [u8]), SignError> {
let (&tag, rest) = input.split_first().ok_or_else(|| bad("truncated DER"))?;
if tag & 0x1F == 0x1F {
return Err(bad("multi-byte DER tags are not supported"));
}
let (&first, rest) = rest.split_first().ok_or_else(|| bad("truncated DER length"))?;
// `trailer` is the two end-of-contents octets, which belong to the element but not to its
// contents.
let (len, rest, trailer) = if first < 0x80 {
(first as usize, rest, 0)
} else if first == 0x80 {
if form == Form::Der {
return Err(bad("indefinite lengths are not allowed in DER"));
}
if tag & 0x20 == 0 {
return Err(bad("an indefinite length needs a constructed element"));
}
(contents_len(rest, form, depth)?, rest, 2)
} else {
let n = (first & 0x7F) as usize;
if n > 4 || rest.len() < n {
return Err(bad("unsupported DER length"));
}
let len = rest[..n].iter().fold(0usize, |acc, b| (acc << 8) | *b as usize);
(len, &rest[n..], 0)
};
let end = len.checked_add(trailer).ok_or_else(|| bad("DER length overflows"))?;
if rest.len() < end {
return Err(bad("DER element runs past the end"));
}
// `end <= rest.len()`, so neither sum below can overflow.
let header = input.len() - rest.len();
Ok((Tlv { tag, value: &rest[..len], raw: &input[..header + end], form }, &rest[end..]))
}
/// Parse `input` as exactly one DER element.
pub fn parse_all(input: &'a [u8]) -> Result<Tlv<'a>, SignError> {
Tlv::only(input, Form::Der)
}
/// Parse `input` as exactly one BER element.
pub fn parse_all_ber(input: &'a [u8]) -> Result<Tlv<'a>, SignError> {
Tlv::only(input, Form::Ber)
}
fn only(input: &'a [u8], form: Form) -> Result<Tlv<'a>, SignError> {
let (t, rest) = Tlv::read(input, form, 0)?;
if !rest.is_empty() {
return Err(bad("trailing bytes after DER element"));
}
Ok(t)
}
/// Whether this element is written with the indefinite length form (BER, never DER). Tags are
/// single-octet here, so the length octet is the second.
pub fn is_indefinite(&self) -> bool {
self.raw.get(1) == Some(&0x80)
self.0.is_indefinite()
}
/// The children of a constructed element, read with the same rules as their parent.
pub fn children(&self) -> Result<Vec<Tlv<'a>>, SignError> {
let mut out = Vec::new();
let mut rest = self.value;
while !rest.is_empty() {
let (t, r) = Tlv::read(rest, self.form, 0)?;
out.push(t);
rest = r;
}
Ok(out)
}
/// Check the tag, for a clear error.
pub fn expect(self, tag: u8, what: &str) -> Result<Tlv<'a>, SignError> {
if self.tag == tag { Ok(self) } else { Err(bad(&format!("{what}: expected tag {tag:#04x}, found {:#04x}", self.tag))) }
}
/// The element inside an EXPLICIT tag.
pub fn inner(&self) -> Result<Tlv<'a>, SignError> {
Tlv::only(self.value, self.form)
}
/// An OCTET STRING's contents, joining the segments of BER's constructed form (X.690 §8.21).
/// Borrowed in the ordinary case, so the common path copies nothing.
pub fn octets(&self, what: &str) -> Result<Cow<'a, [u8]>, SignError> {
self.join(what, 0)
}
fn join(&self, what: &str, depth: usize) -> Result<Cow<'a, [u8]>, SignError> {
/// Deep enough for anything real: a writer that segments at all segments once.
const MAX_DEPTH: usize = 16;
match self.tag {
tag::OCTET_STRING => Ok(Cow::Borrowed(self.value)),
tag::OCTET_STRING_SEGMENTS if self.form == Form::Ber => {
if depth >= MAX_DEPTH {
return Err(bad(&format!("{what}: OCTET STRING segments nested too deeply")));
}
// The join is never larger than the segments it is made of, so this is bounded by
// the input.
let mut out: Vec<u8> = Vec::with_capacity(self.value.len());
for s in self.children()? {
out.extend_from_slice(&s.join(what, depth + 1)?);
}
Ok(Cow::Owned(out))
}
found => Err(bad(&format!("{what}: expected an OCTET STRING, found tag {found:#04x}"))),
}
}
/// An OID in dotted form.
pub fn oid(&self) -> Result<String, SignError> {
if self.tag != tag::OID {
return Err(bad("expected an OID"));
}
oid_to_string(self.value)
}
/// A non-negative INTEGER that fits in a u64.
pub fn u64(&self) -> Result<u64, SignError> {
// (nine bytes only with a 0x00 pad: a nonzero first byte is past 64 bits)
if self.tag != tag::INTEGER
|| self.value.is_empty()
|| self.value.len() > 9
|| self.value[0] & 0x80 != 0
|| (self.value.len() == 9 && self.value[0] != 0)
{
return Err(bad("expected a small non-negative INTEGER"));
}
Ok(self.value.iter().fold(0u64, |acc, b| (acc << 8) | *b as u64))
}
/// A non-negative ENUMERATED that fits in a u64 (same encoding as an INTEGER).
pub fn enumerated(&self) -> Result<u64, SignError> {
if self.tag != tag::ENUMERATED {
return Err(bad("expected an ENUMERATED"));
}
Tlv { tag: tag::INTEGER, ..*self }.u64()
}
/// The magnitude of an INTEGER (leading zero dropped).
pub fn uint_bytes(&self) -> &'a [u8] {
match self.value {
[0, rest @ ..] if !rest.is_empty() => rest,
v => v,
}
self.0.uint_bytes()
}
/// A BIT STRING's bytes (no unused bits allowed).
pub fn bits(&self) -> Result<&'a [u8], SignError> {
match self.value {
[0, rest @ ..] if self.tag == tag::BIT_STRING => Ok(rest),
_ => Err(bad("expected a whole-byte BIT STRING")),
}
}
/// A string type as text (UTF-8, Printable, IA5, T61 as Latin-1, BMP).
pub fn text(&self) -> Option<String> {
match self.tag {
tag::UTF8_STRING | tag::PRINTABLE_STRING | tag::IA5_STRING => Some(String::from_utf8_lossy(self.value).into_owned()),
tag::T61_STRING => Some(self.value.iter().map(|b| *b as char).collect()),
tag::BMP_STRING => {
let units: Vec<u16> = self.value.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
Some(String::from_utf16_lossy(&units))
}
_ => None,
}
self.0.text()
}
/// UTCTime / GeneralizedTime as (year, month, day, hour, minute, second) in UTC.
pub fn parse(input: &'a [u8]) -> Result<(Self, &'a [u8]), SignError> {
shared::Tlv::parse(input).map(|(element, rest)| (Self(element), rest)).map_err(app_error)
}
pub fn parse_ber(input: &'a [u8]) -> Result<(Self, &'a [u8]), SignError> {
shared::Tlv::parse_ber(input).map(|(element, rest)| (Self(element), rest)).map_err(app_error)
}
pub fn parse_all(input: &'a [u8]) -> Result<Self, SignError> {
shared::Tlv::parse_all(input).map(Self).map_err(app_error)
}
pub fn parse_all_ber(input: &'a [u8]) -> Result<Self, SignError> {
shared::Tlv::parse_all_ber(input).map(Self).map_err(app_error)
}
pub fn children(&self) -> Result<Vec<Self>, SignError> {
self.0.children().map(|children| children.into_iter().map(Self).collect()).map_err(app_error)
}
pub fn expect(self, tag: u8, what: &str) -> Result<Self, SignError> {
self.0.expect(tag, what).map(Self).map_err(app_error)
}
pub fn inner(&self) -> Result<Self, SignError> {
self.0.inner().map(Self).map_err(app_error)
}
pub fn octets(&self, what: &str) -> Result<Cow<'a, [u8]>, SignError> {
self.0.octets(what).map_err(app_error)
}
pub fn oid(&self) -> Result<String, SignError> {
self.0.oid().map_err(app_error)
}
pub fn u64(&self) -> Result<u64, SignError> {
self.0.u64().map_err(app_error)
}
pub fn enumerated(&self) -> Result<u64, SignError> {
self.0.enumerated().map_err(app_error)
}
pub fn bits(&self) -> Result<&'a [u8], SignError> {
self.0.bits().map_err(app_error)
}
pub fn time(&self) -> Result<Time, SignError> {
let s = std::str::from_utf8(self.value).map_err(|_| bad("time"))?;
let s = s.strip_suffix('Z').ok_or_else(|| bad("times must be in UTC (Z)"))?;
let num = |r: std::ops::Range<usize>| s.get(r).and_then(|x| x.parse::<u32>().ok()).ok_or_else(|| bad("time"));
let (year, rest) = match self.tag {
tag::UTC_TIME => {
let y = num(0..2)?;
(if y >= 50 { 1900 + y } else { 2000 + y }, 2)
}
tag::GENERALIZED_TIME => (num(0..4)?, 4),
_ => return Err(bad("expected a time")),
};
let t = Time {
year,
month: num(rest..rest + 2)?,
day: num(rest + 2..rest + 4)?,
hour: num(rest + 4..rest + 6)?,
minute: num(rest + 6..rest + 8)?,
second: if s.len() >= rest + 10 { num(rest + 8..rest + 10)? } else { 0 },
};
Ok(t)
self.0.time().map_err(app_error)
}
}
/// How many contents octets an indefinite-length element has: everything up to the matching
/// end-of-contents octets, which have to be there (X.690 §8.1.5). The contents are elements, so
/// finding the end means reading them, and one of those may be indefinite too — hence the depth
/// limit. Every step consumes at least two octets, so the walk always ends.
fn contents_len(input: &[u8], form: Form, depth: usize) -> Result<usize, SignError> {
/// Far deeper than any real file nests, and shallow enough never to exhaust the stack.
const MAX_DEPTH: usize = 48;
if depth >= MAX_DEPTH {
return Err(bad("BER elements nested too deeply"));
}
let mut rest = input;
loop {
match rest {
[] => return Err(bad("an indefinite length with no end-of-contents")),
[0, 0, ..] => return Ok(input.len() - rest.len()),
_ => rest = Tlv::read(rest, form, depth + 1)?.1,
}
}
}
/// `NaiveDate::num_days_from_ce` of 1970-01-01, so the count can be rebased onto the Unix epoch.
const UNIX_EPOCH_DAYS_FROM_CE: i64 = 719_163;
/// A UTC time.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Time {
pub year: u32,
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
pub second: u32,
}
impl Time {
/// From a PDF date (`D:YYYYMMDDHHmmSS±HH'mm'`), converted to UTC.
pub fn from_pdf(s: &str) -> Option<Time> {
let s = s.strip_prefix("D:").unwrap_or(s);
let d = |r: std::ops::Range<usize>, default: u32| s.get(r).map_or(Some(default), |x| x.parse::<u32>().ok());
let mut t =
Time { year: d(0..4, 0)?, month: d(4..6, 1)?, day: d(6..8, 1)?, hour: d(8..10, 0)?, minute: d(10..12, 0)?, second: d(12..14, 0)? };
if t.year == 0 {
return None;
}
let tz = s.get(14..).unwrap_or("");
let sign = match tz.chars().next() {
Some('+') => -1i64,
Some('-') => 1,
_ => 0,
};
if sign != 0 {
let h = tz.get(1..3).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);
let m = tz.get(4..6).and_then(|x| x.parse::<i64>().ok()).unwrap_or(0);
t = t.add_seconds(sign * (h * 3600 + m * 60));
}
Some(t)
}
/// As a PDF date in UTC (`D:YYYYMMDDHHmmSSZ`).
pub fn to_pdf(&self) -> String {
format!("D:{:04}{:02}{:02}{:02}{:02}{:02}Z", self.year, self.month, self.day, self.hour, self.minute, self.second)
}
/// Seconds since 1970-01-01 (proleptic Gregorian).
pub fn unix(&self) -> i64 {
use chrono::Datelike;
// The calendar date goes through chrono; the time of day is a plain second count, as
// before. A date chrono cannot represent (an out-of-range field) reads as the epoch day,
// which no well-formed UTCTime/GeneralizedTime produces.
let days = i32::try_from(self.year)
.ok()
.and_then(|y| chrono::NaiveDate::from_ymd_opt(y, self.month, self.day))
.map_or(0, |d| i64::from(d.num_days_from_ce()) - UNIX_EPOCH_DAYS_FROM_CE);
days * 86_400 + self.hour as i64 * 3600 + self.minute as i64 * 60 + self.second as i64
}
/// The UTC time at `t` seconds since 1970-01-01.
///
/// The calendar date goes through chrono's 400-year Gregorian cycle (146_097 days) so a `t`
/// past `NaiveDate`'s ±262143-year range keeps the proleptic Gregorian date the old hand-rolled
/// converter produced instead of falling back to the epoch. The `year` field is a `u32`, so the
/// year is cast exactly as the old code did (`as u32`, wrapping) — no well-formed signing time
/// is anywhere near that range, and this preserves byte-for-byte the old output everywhere.
pub fn from_unix(t: i64) -> Time {
let (days, secs) = (t.div_euclid(86_400), t.rem_euclid(86_400));
let (year, month, day) = pdfcraft_cos::civil_from_days(days);
Time { year: year as u32, month, day, hour: (secs / 3600) as u32, minute: (secs % 3600 / 60) as u32, second: (secs % 60) as u32 }
}
pub fn add_seconds(&self, s: i64) -> Time {
Time::from_unix(self.unix() + s)
}
/// UTCTime before 2050, GeneralizedTime from then on (RFC 5280 §4.1.2.5).
pub fn encode(&self) -> Vec<u8> {
if (1950..2050).contains(&self.year) {
let s = format!("{:02}{:02}{:02}{:02}{:02}{:02}Z", self.year % 100, self.month, self.day, self.hour, self.minute, self.second);
tlv(tag::UTC_TIME, s.as_bytes())
} else {
let s = format!("{:04}{:02}{:02}{:02}{:02}{:02}Z", self.year, self.month, self.day, self.hour, self.minute, self.second);
tlv(tag::GENERALIZED_TIME, s.as_bytes())
}
}
}
impl std::fmt::Display for Time {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:04}.{:02}.{:02} {:02}:{:02}:{:02} UTC", self.year, self.month, self.day, self.hour, self.minute, self.second)
}
}
fn oid_to_string(v: &[u8]) -> Result<String, SignError> {
let mut arcs: Vec<u64> = Vec::new();
let mut acc = 0u64;
for (i, b) in v.iter().enumerate() {
acc = acc.checked_mul(128).ok_or_else(|| bad("OID arc too large"))? | (b & 0x7F) as u64;
if b & 0x80 == 0 {
if arcs.is_empty() {
let first = (acc / 40).min(2);
arcs.push(first);
arcs.push(acc - first * 40);
} else {
arcs.push(acc);
}
acc = 0;
} else if i + 1 == v.len() {
return Err(bad("truncated OID"));
}
}
Ok(arcs.iter().map(u64::to_string).collect::<Vec<_>>().join("."))
}
// ── writing ─────────────────────────────────────────────────────────────────────────────────
/// One element: identifier, definite length, contents.
pub fn tlv(tag: u8, value: &[u8]) -> Vec<u8> {
let mut out = vec![tag];
let n = value.len();
if n < 0x80 {
out.push(n as u8);
} else {
let bytes: Vec<u8> = n.to_be_bytes().iter().copied().skip_while(|b| *b == 0).collect();
out.push(0x80 | bytes.len() as u8);
out.extend(bytes);
}
out.extend_from_slice(value);
out
}
pub fn seq(parts: &[&[u8]]) -> Vec<u8> {
tlv(tag::SEQUENCE, &parts.concat())
}
/// A SET OF, in DER order (sorted encodings, X.690 §11.6).
pub fn set_of(parts: &[&[u8]]) -> Vec<u8> {
let mut v: Vec<&[u8]> = parts.to_vec();
v.sort();
tlv(tag::SET, &v.concat())
}
pub fn explicit(n: u8, inner: &[u8]) -> Vec<u8> {
tlv(tag::ctx(n), inner)
}
/// The encoding of an OID constant (callers pass only literals from this crate).
// The documented never-crash exception: every caller passes a literal that always parses.
#[allow(clippy::expect_used)]
pub fn oid(dotted: &str) -> Vec<u8> {
let arcs: Vec<u64> = dotted.split('.').map(|a| a.parse().expect("valid OID constant")).collect();
let mut body = Vec::new();
let mut push = |mut v: u64| {
let mut tmp = vec![(v & 0x7F) as u8];
v >>= 7;
while v > 0 {
tmp.push(0x80 | (v & 0x7F) as u8);
v >>= 7;
}
tmp.reverse();
body.extend(tmp);
};
push(arcs[0] * 40 + arcs[1]);
for a in &arcs[2..] {
push(*a);
}
tlv(tag::OID, &body)
}
/// Encode a dotted OID supplied by a caller. Unlike [`oid`], this validates every arc and
/// never panics on malformed input.
pub fn try_oid(dotted: &str) -> Result<Vec<u8>, SignError> {
let mut arcs = dotted.split('.').map(|a| {
if a.is_empty() || !a.bytes().all(|c| c.is_ascii_digit()) {
return Err(bad("invalid OID arc"));
}
a.parse::<u64>().map_err(|_| bad("invalid OID arc"))
});
let first = arcs.next().ok_or_else(|| bad("empty OID"))??;
let second = arcs.next().ok_or_else(|| bad("OID needs two arcs"))??;
if first > 2 || (first < 2 && second >= 40) {
return Err(bad("invalid OID prefix"));
}
let mut body = Vec::new();
let mut push = |mut v: u64| {
let mut tmp = vec![(v & 0x7F) as u8];
v >>= 7;
while v > 0 {
tmp.push(0x80 | (v & 0x7F) as u8);
v >>= 7;
}
tmp.reverse();
body.extend(tmp);
};
let base = first.checked_mul(40).and_then(|b| b.checked_add(second)).ok_or_else(|| bad("invalid OID prefix"))?;
push(base);
for arc in arcs {
push(arc?);
}
Ok(tlv(tag::OID, &body))
}
pub fn uint(bytes: &[u8]) -> Vec<u8> {
let b: &[u8] = match bytes.iter().position(|x| *x != 0) {
Some(i) => &bytes[i..],
None => &[0],
};
if b[0] & 0x80 != 0 {
let mut v = vec![0];
v.extend_from_slice(b);
tlv(tag::INTEGER, &v)
} else {
tlv(tag::INTEGER, b)
}
}
pub fn int(n: u64) -> Vec<u8> {
uint(&n.to_be_bytes())
}
pub fn octets(b: &[u8]) -> Vec<u8> {
tlv(tag::OCTET_STRING, b)
}
pub fn bit_string(b: &[u8]) -> Vec<u8> {
let mut v = vec![0];
v.extend_from_slice(b);
tlv(tag::BIT_STRING, &v)
}
pub fn null() -> Vec<u8> {
vec![tag::NULL, 0]
}
pub fn utf8(s: &str) -> Vec<u8> {
tlv(tag::UTF8_STRING, s.as_bytes())
}
pub fn printable(s: &str) -> Vec<u8> {
tlv(tag::PRINTABLE_STRING, s.as_bytes())
}
pub fn ia5(s: &str) -> Vec<u8> {
tlv(tag::IA5_STRING, s.as_bytes())
}
pub fn boolean(b: bool) -> Vec<u8> {
tlv(tag::BOOLEAN, &[if b { 0xFF } else { 0 }])
}
/// `AlgorithmIdentifier` with optional parameters.
pub fn algorithm(oid_s: &str, params: Option<&[u8]>) -> Vec<u8> {
match params {
Some(p) => seq(&[&oid(oid_s), p]),
None => seq(&[&oid(oid_s)]),
}
shared::try_oid(dotted).map_err(app_error)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shared_adapter_preserves_borrowing_and_error_variants() {
let encoded = seq(&[&int(7), &octets(b"signed bytes")]);
let element = Tlv::parse_all(&encoded).unwrap();
assert_eq!(element.raw.as_ptr(), encoded.as_ptr());
let children = element.children().unwrap();
let bytes = children[1].octets("payload").unwrap();
assert!(matches!(bytes, Cow::Borrowed(_)));
assert_eq!(bytes.as_ptr(), children[1].value.as_ptr());
assert!(matches!(Tlv::parse_all(&[0x30, 0x80, 0, 0]), Err(SignError::Malformed(_))));
assert!(matches!(try_oid("1..2"), Err(SignError::Malformed(_))));
for length in 0..encoded.len() {
let local = Tlv::parse_all(&encoded[..length]).unwrap_err();
let shared = shared::Tlv::parse_all(&encoded[..length]).unwrap_err();
assert_eq!(local.to_string(), shared.to_string());
}
}
#[test]
fn a_nine_byte_integer_needs_a_zero_pad_to_fit_64_bits() {
let tlv = |value: &[u8]| {
+1 -1
View File
@@ -109,7 +109,7 @@ impl Curve {
/// `k · p`, double-and-add from the top bit.
fn mul(&self, k: &BoxedUint, p: &Point) -> Point {
let mut acc: Point = None;
for i in (0..k.bits_vartime()).rev() {
for i in (0..k.bit_width_vartime()).rev() {
acc = self.double(&acc);
if bool::from(k.bit(i)) {
acc = self.add(&acc, p);