12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516 |
- pub mod merkle_stream;
- pub mod tpm;
- pub use merkle_stream::MerkleStream;
- pub mod secret_stream;
- pub use secret_stream::SecretStream;
- use crate::{
- fmt, io, BigArray, BlockMeta, BlockPath, Deserialize, Epoch, Formatter, Hashable, Principal,
- Principaled, Serialize, Writecap, WritecapBody,
- };
- use btserde::{self, from_vec, to_vec, write_to};
- use foreign_types::ForeignType;
- use log::error;
- use openssl::{
- encrypt::{Decrypter as OsslDecrypter, Encrypter as OsslEncrypter},
- error::ErrorStack,
- hash::{hash, DigestBytes, Hasher, MessageDigest},
- nid::Nid,
- pkey::{HasPrivate, HasPublic, PKey, PKeyRef},
- rand::rand_bytes,
- rsa::{Padding as OpensslPadding, Rsa as OsslRsa},
- sign::{Signer as OsslSigner, Verifier as OsslVerifier},
- symm::{decrypt as openssl_decrypt, encrypt as openssl_encrypt, Cipher, Crypter, Mode},
- };
- use serde::{
- de::{self, DeserializeOwned, Deserializer, SeqAccess, Visitor},
- ser::{SerializeStruct, Serializer},
- };
- use std::{
- fmt::Display,
- io::{Read, Write},
- marker::PhantomData,
- num::TryFromIntError,
- };
- use strum_macros::{Display, EnumDiscriminants, FromRepr};
- use zeroize::ZeroizeOnDrop;
- #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
- pub struct Ciphertext<T> {
- data: Vec<u8>,
- phantom: PhantomData<T>,
- }
- impl<T> Ciphertext<T> {
- pub fn new(data: Vec<u8>) -> Ciphertext<T> {
- Ciphertext {
- data,
- phantom: PhantomData,
- }
- }
- }
- pub struct Signed<T> {
- _data: Vec<u8>,
- sig: Signature,
- phantom: PhantomData<T>,
- }
- impl<T> Signed<T> {
- pub fn new(data: Vec<u8>, sig: Signature) -> Signed<T> {
- Signed {
- _data: data,
- sig,
- phantom: PhantomData,
- }
- }
- }
- #[derive(Debug)]
- pub enum Error {
- NoReadCap,
- NoKeyAvailable,
- MissingPrivateKey,
- KeyVariantUnsupported,
- BlockNotEncrypted,
- InvalidHashFormat,
- InvalidSignature,
- IncorrectSize { expected: usize, actual: usize },
- IndexOutOfBounds { index: usize, limit: usize },
- IndivisibleSize { divisor: usize, actual: usize },
- InvalidOffset { actual: usize, limit: usize },
- HashCmpFailure,
- RootHashNotVerified,
- SignatureMismatch(Box<SignatureMismatch>),
- WritecapAuthzErr(WritecapAuthzErr),
- Serde(btserde::Error),
- Io(std::io::Error),
- Custom(Box<dyn std::fmt::Debug + Send + Sync>),
- }
- impl Error {
- pub(crate) fn custom<E: std::fmt::Debug + Send + Sync + 'static>(err: E) -> Error {
- Error::Custom(Box::new(err))
- }
- fn signature_mismatch(expected: Principal, actual: Principal) -> Error {
- Error::SignatureMismatch(Box::new(SignatureMismatch { expected, actual }))
- }
- }
- impl Display for Error {
- fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
- match self {
- Error::NoReadCap => write!(f, "no readcap"),
- Error::NoKeyAvailable => write!(f, "no key available"),
- Error::MissingPrivateKey => write!(f, "private key was missing"),
- Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
- Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
- Error::InvalidHashFormat => write!(f, "invalid format"),
- Error::InvalidSignature => write!(f, "invalid signature"),
- Error::IncorrectSize { expected, actual } => {
- write!(f, "expected size {expected} but got {actual}")
- }
- Error::IndexOutOfBounds { index, limit } => write!(
- f,
- "index {} is out of bounds, it must be strictly less than {}",
- index, limit
- ),
- Error::IndivisibleSize { divisor, actual } => write!(
- f,
- "expected a size which is divisible by {} but got {}",
- divisor, actual
- ),
- Error::InvalidOffset { actual, limit } => write!(
- f,
- "offset {} is out of bounds, it must be strictly less than {}",
- actual, limit
- ),
- Error::HashCmpFailure => write!(f, "hash data are not equal"),
- Error::RootHashNotVerified => write!(f, "root hash is not verified"),
- Error::SignatureMismatch(mismatch) => {
- let actual = &mismatch.actual;
- let expected = &mismatch.expected;
- write!(
- f,
- "expected a signature from {expected} but found one from {actual}"
- )
- }
- Error::WritecapAuthzErr(err) => err.fmt(f),
- Error::Serde(err) => err.fmt(f),
- Error::Io(err) => err.fmt(f),
- Error::Custom(cus) => cus.fmt(f),
- }
- }
- }
- impl std::error::Error for Error {}
- impl From<WritecapAuthzErr> for Error {
- fn from(err: WritecapAuthzErr) -> Self {
- Error::WritecapAuthzErr(err)
- }
- }
- impl From<ErrorStack> for Error {
- fn from(error: ErrorStack) -> Error {
- Error::custom(error)
- }
- }
- impl From<btserde::Error> for Error {
- fn from(error: btserde::Error) -> Error {
- Error::Serde(error)
- }
- }
- impl From<std::io::Error> for Error {
- fn from(error: std::io::Error) -> Error {
- Error::Io(error)
- }
- }
- impl From<TryFromIntError> for Error {
- fn from(err: TryFromIntError) -> Self {
- Error::custom(err)
- }
- }
- impl From<Error> for io::Error {
- fn from(err: Error) -> Self {
- io::Error::new(io::ErrorKind::Other, err)
- }
- }
- impl From<crate::Error> for Error {
- fn from(err: crate::Error) -> Self {
- Error::custom(err)
- }
- }
- pub(crate) type Result<T> = std::result::Result<T, Error>;
- #[derive(Debug)]
- pub struct SignatureMismatch {
- pub actual: Principal,
- pub expected: Principal,
- }
- pub fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
- let mut array = [0; LEN];
- rand_bytes(&mut array)?;
- Ok(array)
- }
- pub fn rand_vec(len: usize) -> Result<Vec<u8>> {
- let mut vec = vec![0; len];
- rand_bytes(&mut vec)?;
- Ok(vec)
- }
- pub trait Op: Sized {
-
- type Arg;
-
- fn init(arg: Self::Arg) -> Result<Self>;
-
- fn update(&mut self, data: &[u8]) -> Result<()>;
-
-
- fn finish_into(self, buf: &mut [u8]) -> Result<usize>;
- }
- pub trait HashOp: Op {
-
- type Hash: Hash;
-
- fn kind(&self) -> HashKind;
-
- fn finish(self) -> Result<Self::Hash>;
- }
- pub struct OsslHashOp<H> {
- hasher: Hasher,
- phantom: PhantomData<H>,
- kind: HashKind,
- }
- impl<H> Op for OsslHashOp<H> {
- type Arg = HashKind;
- fn init(arg: Self::Arg) -> Result<Self> {
- let hasher = Hasher::new(arg.into())?;
- let phantom = PhantomData;
- Ok(OsslHashOp {
- hasher,
- phantom,
- kind: arg,
- })
- }
- fn update(&mut self, data: &[u8]) -> Result<()> {
- Ok(self.hasher.update(data)?)
- }
- fn finish_into(mut self, buf: &mut [u8]) -> Result<usize> {
- if buf.len() < self.kind.len() {
- return Err(Error::IncorrectSize {
- expected: self.kind.len(),
- actual: buf.len(),
- });
- }
- let digest = self.hasher.finish()?;
- let slice = digest.as_ref();
- buf.copy_from_slice(slice);
- Ok(slice.len())
- }
- }
- impl<H: Hash + From<DigestBytes>> HashOp for OsslHashOp<H> {
- type Hash = H;
- fn kind(&self) -> HashKind {
- self.kind
- }
- fn finish(mut self) -> Result<Self::Hash> {
- let digest = self.hasher.finish()?;
- Ok(H::from(digest))
- }
- }
- pub struct HashStream<T, Op: HashOp> {
- inner: T,
- op: Op,
- update_failed: bool,
- }
- impl<T, Op: HashOp> HashStream<T, Op> {
-
- pub fn new(inner: T, op: Op) -> HashStream<T, Op> {
- HashStream {
- inner,
- op,
- update_failed: false,
- }
- }
-
-
- pub fn finish_into(self, buf: &mut [u8]) -> Result<usize> {
- if self.update_failed {
- return Err(Error::custom(
- "HashStream::finish_into can't produce result due to HashOp update failure",
- ));
- }
- self.op.finish_into(buf)
- }
-
- pub fn finish(self) -> Result<Op::Hash> {
- if self.update_failed {
- return Err(Error::custom(
- "HashStream::finish can't produce result due to HashOp update failure",
- ));
- }
- self.op.finish()
- }
- }
- impl<T: Read, Op: HashOp> Read for HashStream<T, Op> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- if self.update_failed {
- return Err(Error::custom(
- "HashStream::read can't continue due to previous HashOp update failure",
- )
- .into());
- }
- let read = self.inner.read(buf)?;
- if read > 0 {
- if let Err(err) = self.op.update(&buf[..read]) {
- self.update_failed = true;
- error!("HashWrap::read failed to update HashOp: {}", err);
- }
- }
- Ok(read)
- }
- }
- impl<T: Write, Op: HashOp> Write for HashStream<T, Op> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.op.update(buf)?;
- self.inner.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.inner.flush()
- }
- }
- pub trait Hash: AsRef<[u8]> + AsMut<[u8]> + Sized {
-
- type Op: HashOp;
-
- type Arg;
-
- fn new(arg: Self::Arg) -> Self;
-
- fn kind(&self) -> HashKind;
-
- fn start_op(&self) -> Result<Self::Op>;
- }
- pub trait DefaultHash: Hash {
- fn default() -> Self;
- }
- impl<A: Default, T: Hash<Arg = A>> DefaultHash for T {
- fn default() -> Self {
- Self::new(A::default())
- }
- }
- #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
- pub struct Sha2_256([u8; Self::LEN]);
- impl Sha2_256 {
- pub const KIND: HashKind = HashKind::Sha2_256;
- pub const LEN: usize = Self::KIND.len();
- }
- impl AsRef<[u8]> for Sha2_256 {
- fn as_ref(&self) -> &[u8] {
- self.0.as_slice()
- }
- }
- impl AsMut<[u8]> for Sha2_256 {
- fn as_mut(&mut self) -> &mut [u8] {
- self.0.as_mut_slice()
- }
- }
- impl From<DigestBytes> for Sha2_256 {
- fn from(value: DigestBytes) -> Self {
- let mut hash = Sha2_256::new(());
-
- hash.as_mut().copy_from_slice(value.as_ref());
- hash
- }
- }
- impl From<[u8; Self::LEN]> for Sha2_256 {
- fn from(value: [u8; Self::LEN]) -> Self {
- Sha2_256(value)
- }
- }
- impl From<Sha2_256> for [u8; Sha2_256::LEN] {
- fn from(value: Sha2_256) -> Self {
- value.0
- }
- }
- impl Hash for Sha2_256 {
- type Op = OsslHashOp<Sha2_256>;
- type Arg = ();
- fn new(_: Self::Arg) -> Self {
- Sha2_256([0u8; Self::KIND.len()])
- }
- fn kind(&self) -> HashKind {
- Self::KIND
- }
- fn start_op(&self) -> Result<Self::Op> {
- OsslHashOp::init(Self::KIND)
- }
- }
- #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
- pub struct Sha2_512(#[serde(with = "BigArray")] [u8; Self::LEN]);
- impl Sha2_512 {
- pub const KIND: HashKind = HashKind::Sha2_512;
- pub const LEN: usize = Self::KIND.len();
- }
- impl AsRef<[u8]> for Sha2_512 {
- fn as_ref(&self) -> &[u8] {
- self.0.as_slice()
- }
- }
- impl AsMut<[u8]> for Sha2_512 {
- fn as_mut(&mut self) -> &mut [u8] {
- self.0.as_mut_slice()
- }
- }
- impl From<DigestBytes> for Sha2_512 {
- fn from(value: DigestBytes) -> Self {
- let mut hash = Sha2_512::new(());
- hash.as_mut().copy_from_slice(value.as_ref());
- hash
- }
- }
- impl From<[u8; Self::LEN]> for Sha2_512 {
- fn from(value: [u8; Self::LEN]) -> Self {
- Self(value)
- }
- }
- impl From<Sha2_512> for [u8; Sha2_512::LEN] {
- fn from(value: Sha2_512) -> Self {
- value.0
- }
- }
- impl Hash for Sha2_512 {
- type Op = OsslHashOp<Sha2_512>;
- type Arg = ();
- fn new(_: Self::Arg) -> Self {
- Sha2_512([0u8; Self::LEN])
- }
- fn kind(&self) -> HashKind {
- Self::KIND
- }
- fn start_op(&self) -> Result<Self::Op> {
- OsslHashOp::init(Self::KIND)
- }
- }
- #[derive(
- Debug,
- PartialEq,
- Eq,
- Serialize,
- Deserialize,
- Hashable,
- Clone,
- EnumDiscriminants,
- PartialOrd,
- Ord,
- )]
- #[strum_discriminants(derive(FromRepr, Display, Serialize, Deserialize))]
- #[strum_discriminants(name(HashKind))]
- pub enum VarHash {
- Sha2_256(Sha2_256),
- Sha2_512(Sha2_512),
- }
- impl Default for HashKind {
- fn default() -> HashKind {
- HashKind::Sha2_256
- }
- }
- impl Default for VarHash {
- fn default() -> Self {
- HashKind::default().into()
- }
- }
- impl HashKind {
- #[allow(clippy::len_without_is_empty)]
- pub const fn len(self) -> usize {
- match self {
- HashKind::Sha2_256 => 32,
- HashKind::Sha2_512 => 64,
- }
- }
- pub fn digest<'a, I: Iterator<Item = &'a [u8]>>(self, dest: &mut [u8], parts: I) -> Result<()> {
- if dest.len() != self.len() {
- return Err(Error::IncorrectSize {
- expected: self.len(),
- actual: dest.len(),
- });
- }
- let mut hasher = Hasher::new(self.into())?;
- for part in parts {
- hasher.update(part)?;
- }
- let hash = hasher.finish()?;
- dest.copy_from_slice(&hash);
- Ok(())
- }
- }
- impl TryFrom<MessageDigest> for HashKind {
- type Error = Error;
- fn try_from(value: MessageDigest) -> Result<Self> {
- let nid = value.type_();
- if Nid::SHA256 == nid {
- Ok(HashKind::Sha2_256)
- } else if Nid::SHA512 == nid {
- Ok(HashKind::Sha2_512)
- } else {
- Err(Error::custom(format!(
- "Unsupported MessageDigest with NID: {:?}",
- nid
- )))
- }
- }
- }
- impl From<HashKind> for MessageDigest {
- fn from(kind: HashKind) -> Self {
- match kind {
- HashKind::Sha2_256 => MessageDigest::sha256(),
- HashKind::Sha2_512 => MessageDigest::sha512(),
- }
- }
- }
- impl VarHash {
-
-
- const HASH_SEP: char = '!';
- pub fn kind(&self) -> HashKind {
- self.into()
- }
- pub fn as_slice(&self) -> &[u8] {
- self.as_ref()
- }
- pub fn as_mut_slice(&mut self) -> &mut [u8] {
- self.as_mut()
- }
- }
- impl From<HashKind> for VarHash {
- fn from(kind: HashKind) -> VarHash {
- match kind {
- HashKind::Sha2_256 => VarHash::Sha2_256(Sha2_256::default()),
- HashKind::Sha2_512 => VarHash::Sha2_512(Sha2_512::default()),
- }
- }
- }
- impl AsRef<[u8]> for VarHash {
- fn as_ref(&self) -> &[u8] {
- match self {
- VarHash::Sha2_256(arr) => arr.as_ref(),
- VarHash::Sha2_512(arr) => arr.as_ref(),
- }
- }
- }
- impl AsMut<[u8]> for VarHash {
- fn as_mut(&mut self) -> &mut [u8] {
- match self {
- VarHash::Sha2_256(arr) => arr.as_mut(),
- VarHash::Sha2_512(arr) => arr.as_mut(),
- }
- }
- }
- impl TryFrom<MessageDigest> for VarHash {
- type Error = Error;
- fn try_from(value: MessageDigest) -> Result<Self> {
- let kind: HashKind = value.try_into()?;
- Ok(kind.into())
- }
- }
- impl Hash for VarHash {
- type Op = VarHashOp;
- type Arg = HashKind;
- fn new(arg: Self::Arg) -> Self {
- arg.into()
- }
- fn kind(&self) -> HashKind {
- self.kind()
- }
- fn start_op(&self) -> Result<Self::Op> {
- VarHashOp::init(self.kind())
- }
- }
- impl TryFrom<&str> for VarHash {
- type Error = Error;
- fn try_from(string: &str) -> Result<VarHash> {
- let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
- if split.len() != 2 {
- return Err(Error::InvalidHashFormat);
- };
- let second = split.pop().ok_or(Error::InvalidHashFormat)?;
- let first = split
- .pop()
- .ok_or(Error::InvalidHashFormat)?
- .parse::<usize>()
- .map_err(|_| Error::InvalidHashFormat)?;
- let mut hash = VarHash::from(HashKind::from_repr(first).ok_or(Error::InvalidHashFormat)?);
- base64_url::decode_to_slice(second, hash.as_mut()).map_err(|_| Error::InvalidHashFormat)?;
- Ok(hash)
- }
- }
- impl Display for VarHash {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let hash_kind: HashKind = self.into();
- let hash_data = base64_url::encode(self.as_ref());
- write!(f, "{}{}{hash_data}", hash_kind as u32, VarHash::HASH_SEP)
- }
- }
- pub struct VarHashOp {
- kind: HashKind,
- hasher: Hasher,
- }
- impl Op for VarHashOp {
- type Arg = HashKind;
- fn init(arg: Self::Arg) -> Result<Self> {
- let hasher = Hasher::new(arg.into())?;
- Ok(VarHashOp { kind: arg, hasher })
- }
- fn update(&mut self, data: &[u8]) -> Result<()> {
- Ok(self.hasher.update(data)?)
- }
- fn finish_into(mut self, buf: &mut [u8]) -> Result<usize> {
- if buf.len() < self.kind.len() {
- return Err(Error::IncorrectSize {
- expected: self.kind.len(),
- actual: buf.len(),
- });
- }
- let digest = self.hasher.finish()?;
- let slice = digest.as_ref();
- buf.copy_from_slice(slice);
- Ok(slice.len())
- }
- }
- impl HashOp for VarHashOp {
- type Hash = VarHash;
- fn kind(&self) -> HashKind {
- self.kind
- }
- fn finish(mut self) -> Result<Self::Hash> {
- let digest = self.hasher.finish()?;
- let mut hash: VarHash = self.kind.into();
- hash.as_mut().copy_from_slice(digest.as_ref());
- Ok(hash)
- }
- }
- #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Default)]
- pub struct Signature {
- kind: Sign,
- data: Vec<u8>,
- }
- impl Signature {
- pub fn empty(kind: Sign) -> Signature {
- let data = vec![0; kind.key_len() as usize];
- Signature { kind, data }
- }
- #[cfg(test)]
- pub fn copy_from(kind: Sign, from: &[u8]) -> Signature {
- let mut data = vec![0; kind.key_len() as usize];
- data.as_mut_slice().copy_from_slice(from);
- Signature { kind, data }
- }
- pub fn as_slice(&self) -> &[u8] {
- self.data.as_slice()
- }
- pub fn as_mut_slice(&mut self) -> &mut [u8] {
- self.data.as_mut_slice()
- }
- }
- impl AsRef<[u8]> for Signature {
- fn as_ref(&self) -> &[u8] {
- self.as_slice()
- }
- }
- impl AsMut<[u8]> for Signature {
- fn as_mut(&mut self) -> &mut [u8] {
- self.as_mut_slice()
- }
- }
- #[derive(Serialize, Deserialize)]
- struct TaggedCiphertext<T, U> {
- aad: U,
- ciphertext: Ciphertext<T>,
- tag: Vec<u8>,
- }
- #[derive(EnumDiscriminants, ZeroizeOnDrop)]
- #[strum_discriminants(name(AeadKeyKind))]
- #[strum_discriminants(derive(Serialize, Deserialize))]
- pub enum AeadKey {
- AesGcm256 {
- key: [u8; AeadKeyKind::AesGcm256.key_len()],
- iv: [u8; AeadKeyKind::AesGcm256.iv_len()],
- },
- }
- impl AeadKeyKind {
- const fn key_len(self) -> usize {
- match self {
- AeadKeyKind::AesGcm256 => 32,
- }
- }
- const fn iv_len(self) -> usize {
- match self {
- AeadKeyKind::AesGcm256 => 16,
- }
- }
- }
- fn array_from<const N: usize>(slice: &[u8]) -> Result<[u8; N]> {
- let slice_len = slice.len();
- if N != slice_len {
- return Err(Error::IncorrectSize {
- actual: slice_len,
- expected: N,
- });
- }
- let mut array = [0u8; N];
- array.copy_from_slice(slice);
- Ok(array)
- }
- impl AeadKey {
- pub fn new(kind: AeadKeyKind) -> Result<AeadKey> {
- match kind {
- AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
- key: rand_array()?,
- iv: rand_array()?,
- }),
- }
- }
- fn copy_components(kind: AeadKeyKind, key_buf: &[u8], iv_buf: &[u8]) -> Result<AeadKey> {
- match kind {
- AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
- key: array_from(key_buf)?,
- iv: array_from(iv_buf)?,
- }),
- }
- }
- fn encrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
- &self,
- aad: U,
- plaintext: &T,
- ) -> Result<TaggedCiphertext<T, U>> {
- let (cipher, key, iv, mut tag) = match self {
- AeadKey::AesGcm256 { key, iv } => (
- Cipher::aes_256_gcm(),
- key.as_slice(),
- iv.as_slice(),
- vec![0u8; 16],
- ),
- };
- let aad_data = to_vec(&aad)?;
- let plaintext_buf = to_vec(&plaintext)?;
- let mut ciphertext = vec![0u8; plaintext_buf.len() + cipher.block_size()];
- let mut crypter = Crypter::new(cipher, Mode::Encrypt, key, Some(iv))?;
- crypter.aad_update(&aad_data)?;
- let mut count = crypter.update(&plaintext_buf, &mut ciphertext)?;
- count += crypter.finalize(&mut ciphertext[count..])?;
- ciphertext.truncate(count);
- crypter.get_tag(&mut tag)?;
- Ok(TaggedCiphertext {
- aad,
- ciphertext: Ciphertext::new(ciphertext),
- tag,
- })
- }
- fn decrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
- &self,
- tagged: &TaggedCiphertext<T, U>,
- ) -> Result<T> {
- let ciphertext = &tagged.ciphertext.data;
- let (cipher, key, iv) = match self {
- AeadKey::AesGcm256 { key, iv } => {
- (Cipher::aes_256_gcm(), key.as_slice(), iv.as_slice())
- }
- };
- let mut plaintext = vec![0u8; ciphertext.len() + cipher.block_size()];
- let mut crypter = Crypter::new(cipher, Mode::Decrypt, key, Some(iv))?;
- crypter.set_tag(&tagged.tag)?;
- let aad_buf = to_vec(&tagged.aad)?;
- crypter.aad_update(&aad_buf)?;
- let mut count = crypter.update(ciphertext, &mut plaintext)?;
- count += crypter.finalize(&mut plaintext[count..])?;
- plaintext.truncate(count);
- Ok(from_vec(&plaintext)?)
- }
- }
- #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, EnumDiscriminants, ZeroizeOnDrop)]
- #[strum_discriminants(name(SymKeyKind))]
- pub enum SymKey {
-
-
-
- Aes256Cbc { key: [u8; 32], iv: [u8; 16] },
-
- Aes256Ctr { key: [u8; 32], iv: [u8; 16] },
- }
- struct SymParams<'a> {
- cipher: Cipher,
- key: &'a [u8],
- iv: Option<&'a [u8]>,
- }
- impl SymKey {
- pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
- match kind {
- SymKeyKind::Aes256Cbc => Ok(SymKey::Aes256Cbc {
- key: rand_array()?,
- iv: rand_array()?,
- }),
- SymKeyKind::Aes256Ctr => Ok(SymKey::Aes256Ctr {
- key: rand_array()?,
- iv: rand_array()?,
- }),
- }
- }
- fn params(&self) -> SymParams {
- let (cipher, key, iv) = match self {
- SymKey::Aes256Cbc { key, iv } => (Cipher::aes_256_cbc(), key, Some(iv.as_slice())),
- SymKey::Aes256Ctr { key, iv } => (Cipher::aes_256_ctr(), key, Some(iv.as_slice())),
- };
- SymParams { cipher, key, iv }
- }
- fn block_size(&self) -> usize {
- let SymParams { cipher, .. } = self.params();
- cipher.block_size()
- }
-
- fn expansion_sz(&self) -> usize {
- match self {
- SymKey::Aes256Cbc { .. } => 16,
- SymKey::Aes256Ctr { .. } => 0,
- }
- }
- fn to_encrypter(&self) -> Result<Crypter> {
- let SymParams { cipher, key, iv } = self.params();
- Ok(Crypter::new(cipher, Mode::Encrypt, key, iv)?)
- }
- fn to_decrypter(&self) -> Result<Crypter> {
- let SymParams { cipher, key, iv } = self.params();
- Ok(Crypter::new(cipher, Mode::Decrypt, key, iv)?)
- }
- pub fn key_slice(&self) -> &[u8] {
- let SymParams { key, .. } = self.params();
- key
- }
- pub fn iv_slice(&self) -> Option<&[u8]> {
- let SymParams { iv, .. } = self.params();
- iv
- }
- }
- impl Encrypter for SymKey {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- let SymParams { cipher, key, iv } = self.params();
- Ok(openssl_encrypt(cipher, key, iv, slice)?)
- }
- }
- impl Decrypter for SymKey {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- let SymParams { cipher, key, iv } = self.params();
- Ok(openssl_decrypt(cipher, key, iv, slice)?)
- }
- }
- impl Default for SymKeyKind {
- fn default() -> Self {
- SymKeyKind::Aes256Ctr
- }
- }
- #[repr(u32)]
- #[derive(Debug, Display, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
- pub enum KeyLen {
- Bits256 = 32,
- Bits512 = 64,
- Bits2048 = 256,
- Bits3072 = 384,
- Bits4096 = 512,
- }
- impl KeyLen {
- const fn bits(self) -> u32 {
- 8 * self as u32
- }
- }
- pub trait Scheme:
- for<'de> Deserialize<'de> + Serialize + Copy + std::fmt::Debug + PartialEq + Into<Self::Kind>
- {
- type Kind: Scheme;
- fn as_enum(self) -> SchemeKind;
- fn hash_kind(&self) -> HashKind;
- fn padding(&self) -> Option<OpensslPadding>;
- fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>>;
- fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>>;
- fn generate(self) -> Result<AsymKeyPair<Self::Kind>>;
- fn key_len(self) -> KeyLen;
- fn message_digest(&self) -> MessageDigest {
- self.hash_kind().into()
- }
- }
- pub enum SchemeKind {
- Sign(Sign),
- Encrypt(Encrypt),
- }
- #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
- pub enum Encrypt {
- RsaEsOaep(RsaEsOaep),
- }
- impl Scheme for Encrypt {
- type Kind = Encrypt;
- fn as_enum(self) -> SchemeKind {
- SchemeKind::Encrypt(self)
- }
- fn hash_kind(&self) -> HashKind {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.hash_kind(),
- }
- }
- fn padding(&self) -> Option<OpensslPadding> {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.padding(),
- }
- }
- fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.public_from_der(der),
- }
- }
- fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.private_from_der(der),
- }
- }
- fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.generate(),
- }
- }
- fn key_len(self) -> KeyLen {
- match self {
- Encrypt::RsaEsOaep(inner) => inner.key_len(),
- }
- }
- }
- impl Encrypt {
- pub const RSA_OAEP_2048_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
- key_len: KeyLen::Bits2048,
- hash_kind: HashKind::Sha2_256,
- });
- pub const RSA_OAEP_3072_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
- key_len: KeyLen::Bits3072,
- hash_kind: HashKind::Sha2_256,
- });
- }
- #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
- pub enum Sign {
- RsaSsaPss(RsaSsaPss),
- }
- impl Default for Sign {
- fn default() -> Self {
- Self::RSA_PSS_2048_SHA_256
- }
- }
- impl Scheme for Sign {
- type Kind = Sign;
- fn as_enum(self) -> SchemeKind {
- SchemeKind::Sign(self)
- }
- fn hash_kind(&self) -> HashKind {
- match self {
- Sign::RsaSsaPss(inner) => inner.hash_kind(),
- }
- }
- fn padding(&self) -> Option<OpensslPadding> {
- match self {
- Sign::RsaSsaPss(inner) => inner.padding(),
- }
- }
- fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
- match self {
- Sign::RsaSsaPss(inner) => inner.public_from_der(der),
- }
- }
- fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
- match self {
- Sign::RsaSsaPss(inner) => inner.private_from_der(der),
- }
- }
- fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
- match self {
- Sign::RsaSsaPss(inner) => inner.generate(),
- }
- }
- fn key_len(self) -> KeyLen {
- self.key_len_const()
- }
- }
- impl Sign {
- pub const RSA_PSS_2048_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
- key_bits: KeyLen::Bits2048,
- hash_kind: HashKind::Sha2_256,
- });
- pub const RSA_PSS_3072_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
- key_bits: KeyLen::Bits3072,
- hash_kind: HashKind::Sha2_256,
- });
- const fn key_len_const(self) -> KeyLen {
- match self {
- Sign::RsaSsaPss(inner) => inner.key_bits,
- }
- }
- }
- enum Rsa {}
- impl Rsa {
-
- const EXP: u32 = 65537;
- fn generate<S: Scheme>(scheme: S) -> Result<AsymKeyPair<S>> {
- let key = OsslRsa::generate(scheme.key_len().bits())?;
-
- let public_der = key.public_key_to_der()?;
- let private_der = key.private_key_to_der()?;
- let public = AsymKey::<Public, S>::new(scheme, &public_der)?;
- let private = AsymKey::<Private, S>::new(scheme, &private_der)?;
- Ok(AsymKeyPair { public, private })
- }
- }
- #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
- pub struct RsaEsOaep {
- key_len: KeyLen,
- hash_kind: HashKind,
- }
- impl Scheme for RsaEsOaep {
- type Kind = Encrypt;
- fn as_enum(self) -> SchemeKind {
- SchemeKind::Encrypt(self.into())
- }
- fn hash_kind(&self) -> HashKind {
- self.hash_kind
- }
- fn padding(&self) -> Option<OpensslPadding> {
- Some(OpensslPadding::PKCS1_OAEP)
- }
- fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
- Ok(PKey::public_key_from_der(der)?.conv_pub())
- }
- fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
- Ok(PKey::private_key_from_der(der)?.conv_priv())
- }
- fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
- Rsa::generate(self.into())
- }
- fn key_len(self) -> KeyLen {
- self.key_len
- }
- }
- impl From<RsaEsOaep> for Encrypt {
- fn from(scheme: RsaEsOaep) -> Self {
- Encrypt::RsaEsOaep(scheme)
- }
- }
- #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
- pub struct RsaSsaPss {
- key_bits: KeyLen,
- hash_kind: HashKind,
- }
- impl Scheme for RsaSsaPss {
- type Kind = Sign;
- fn as_enum(self) -> SchemeKind {
- SchemeKind::Sign(self.into())
- }
- fn hash_kind(&self) -> HashKind {
- self.hash_kind
- }
- fn padding(&self) -> Option<OpensslPadding> {
- Some(OpensslPadding::PKCS1_PSS)
- }
- fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
- Ok(PKey::public_key_from_der(der)?.conv_pub())
- }
- fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
- Ok(PKey::private_key_from_der(der)?.conv_priv())
- }
- fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
- Rsa::generate(self.into())
- }
- fn key_len(self) -> KeyLen {
- self.key_bits
- }
- }
- impl From<RsaSsaPss> for Sign {
- fn from(scheme: RsaSsaPss) -> Self {
- Sign::RsaSsaPss(scheme)
- }
- }
- pub trait KeyPrivacy {}
- #[derive(Clone, Debug)]
- pub enum Public {}
- impl KeyPrivacy for Public {}
- unsafe impl HasPublic for Public {}
- #[derive(Debug, Clone)]
- pub enum Private {}
- impl KeyPrivacy for Private {}
- unsafe impl HasPrivate for Private {}
- trait PKeyExt<T> {
-
-
- fn conv_pkey<U>(self) -> PKey<U>;
-
- fn conv_pub(self) -> PKey<Public>;
-
- fn conv_priv(self) -> PKey<Private>;
- }
- impl<T> PKeyExt<T> for PKey<T> {
- fn conv_pkey<U>(self) -> PKey<U> {
- let ptr = self.as_ptr();
- let new_pkey = unsafe { PKey::from_ptr(ptr) };
- std::mem::forget(self);
- new_pkey
- }
- fn conv_pub(self) -> PKey<Public> {
- self.conv_pkey()
- }
- fn conv_priv(self) -> PKey<Private> {
- self.conv_pkey()
- }
- }
- #[derive(Debug, Clone)]
- pub struct AsymKey<P, S> {
- scheme: S,
- pkey: PKey<P>,
- }
- impl<P, S: Copy> AsymKey<P, S> {
- pub fn scheme(&self) -> S {
- self.scheme
- }
- }
- pub type AsymKeyPub<S> = AsymKey<Public, S>;
- impl<S: Scheme> AsymKey<Public, S> {
- pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Public, S>> {
- let pkey = scheme.public_from_der(der)?;
- Ok(AsymKey { scheme, pkey })
- }
- }
- impl<S: Scheme> AsymKey<Private, S> {
- pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Private, S>> {
- let pkey = scheme.private_from_der(der)?;
- Ok(AsymKey { scheme, pkey })
- }
- }
- impl<'de, S: Scheme> Deserialize<'de> for AsymKey<Public, S> {
- fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
- const FIELDS: &[&str] = &["scheme", "pkey"];
- struct StructVisitor<S: Scheme>(PhantomData<S>);
- impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
- type Value = AsymKey<Public, S>;
- fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- formatter.write_fmt(format_args!("struct {}", stringify!(AsymKey)))
- }
- fn visit_seq<V: SeqAccess<'de>>(
- self,
- mut seq: V,
- ) -> std::result::Result<Self::Value, V::Error> {
- let scheme: S = seq
- .next_element()?
- .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
- let der: Vec<u8> = seq
- .next_element()?
- .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
- AsymKey::<Public, _>::new(scheme, der.as_slice()).map_err(de::Error::custom)
- }
- }
- d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
- }
- }
- impl<S: Scheme> Serialize for AsymKey<Public, S> {
- fn serialize<T: Serializer>(&self, s: T) -> std::result::Result<T::Ok, T::Error> {
- let mut struct_s = s.serialize_struct(stringify!(AsymKey), 2)?;
- struct_s.serialize_field("scheme", &self.scheme)?;
- let der = self.pkey.public_key_to_der().unwrap();
- struct_s.serialize_field("pkey", der.as_slice())?;
- struct_s.end()
- }
- }
- impl<S: Scheme> PartialEq for AsymKey<Public, S> {
- fn eq(&self, other: &Self) -> bool {
- self.scheme == other.scheme && self.pkey.public_eq(&other.pkey)
- }
- }
- impl Principaled for AsymKey<Public, Sign> {
- fn principal_of_kind(&self, kind: HashKind) -> Principal {
- let der = self.pkey.public_key_to_der().unwrap();
- let bytes = hash(kind.into(), der.as_slice()).unwrap();
- let mut hash_buf = VarHash::from(kind);
- hash_buf.as_mut().copy_from_slice(&bytes);
- Principal(hash_buf)
- }
- }
- impl Encrypter for AsymKey<Public, Encrypt> {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- let mut encrypter = OsslEncrypter::new(&self.pkey)?;
- if let Some(padding) = self.scheme.padding() {
- encrypter.set_rsa_padding(padding)?;
- }
- {
- let Encrypt::RsaEsOaep(inner) = self.scheme;
- encrypter.set_rsa_oaep_md(inner.message_digest())?;
- }
- let buffer_len = encrypter.encrypt_len(slice)?;
- let mut ciphertext = vec![0; buffer_len];
- let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)?;
- ciphertext.truncate(ciphertext_len);
- Ok(ciphertext)
- }
- }
- impl Decrypter for AsymKey<Private, Encrypt> {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- let mut decrypter = OsslDecrypter::new(&self.pkey)?;
- if let Some(padding) = self.scheme.padding() {
- decrypter.set_rsa_padding(padding)?;
- }
- {
- let Encrypt::RsaEsOaep(inner) = self.scheme;
- decrypter.set_rsa_oaep_md(inner.message_digest())?;
- }
- let buffer_len = decrypter.decrypt_len(slice)?;
- let mut plaintext = vec![0; buffer_len];
- let plaintext_len = decrypter.decrypt(slice, &mut plaintext)?;
- plaintext.truncate(plaintext_len);
- Ok(plaintext)
- }
- }
- impl Signer for AsymKey<Private, Sign> {
- type Op<'s> = OsslSignOp<'s>;
- fn init_sign(&self) -> Result<Self::Op<'_>> {
- OsslSignOp::init((self.scheme, self.pkey.as_ref()))
- }
- fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
- let mut signer = OsslSigner::new(self.scheme.message_digest(), &self.pkey)?;
- if let Some(padding) = self.scheme.padding() {
- signer.set_rsa_padding(padding)?;
- }
- for part in parts {
- signer.update(part)?;
- }
- let mut signature = Signature::empty(self.scheme);
- signer.sign(signature.as_mut_slice())?;
- Ok(signature)
- }
- }
- impl Verifier for AsymKey<Public, Sign> {
- type Op<'v> = OsslVerifyOp<'v>;
- fn init_verify(&self) -> Result<Self::Op<'_>> {
- OsslVerifyOp::init((self.scheme, self.pkey.as_ref()))
- }
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
- let mut verifier = OsslVerifier::new(self.scheme.message_digest(), &self.pkey)?;
- if let Some(padding) = self.scheme.padding() {
- verifier.set_rsa_padding(padding)?;
- }
- for part in parts {
- verifier.update(part)?;
- }
- if verifier.verify(signature)? {
- Ok(())
- } else {
- Err(Error::InvalidSignature)
- }
- }
- }
- #[derive(Clone)]
- pub struct AsymKeyPair<S: Scheme> {
- public: AsymKey<Public, S>,
- private: AsymKey<Private, S>,
- }
- impl<S: Scheme> AsymKeyPair<S> {
- pub fn new(scheme: S, public_der: &[u8], private_der: &[u8]) -> Result<AsymKeyPair<S>> {
- let public = AsymKey::<Public, _>::new(scheme, public_der)?;
- let private = AsymKey::<Private, _>::new(scheme, private_der)?;
- Ok(AsymKeyPair { public, private })
- }
- }
- impl Principaled for AsymKeyPair<Sign> {
- fn principal_of_kind(&self, kind: HashKind) -> Principal {
- self.public.principal_of_kind(kind)
- }
- }
- impl Encrypter for AsymKeyPair<Encrypt> {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- self.public.encrypt(slice)
- }
- }
- impl Decrypter for AsymKeyPair<Encrypt> {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- self.private.decrypt(slice)
- }
- }
- impl Signer for AsymKeyPair<Sign> {
- type Op<'s> = <AsymKey<Private, Sign> as Signer>::Op<'s>;
- fn init_sign(&self) -> Result<Self::Op<'_>> {
- self.private.init_sign()
- }
- fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
- self.private.sign(parts)
- }
- }
- impl Verifier for AsymKeyPair<Sign> {
- type Op<'v> = OsslVerifyOp<'v>;
- fn init_verify(&self) -> Result<Self::Op<'_>> {
- self.public.init_verify()
- }
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
- self.public.verify(parts, signature)
- }
- }
- #[derive(Debug, Clone, Serialize, Deserialize)]
- pub struct PublicCreds {
- sign: AsymKeyPub<Sign>,
- enc: AsymKeyPub<Encrypt>,
- }
- impl Principaled for PublicCreds {
- fn principal_of_kind(&self, kind: HashKind) -> Principal {
- self.sign.principal_of_kind(kind)
- }
- }
- impl Encrypter for PublicCreds {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- self.enc.encrypt(slice)
- }
- }
- impl Verifier for PublicCreds {
- type Op<'v> = OsslVerifyOp<'v>;
- fn init_verify(&self) -> Result<Self::Op<'_>> {
- self.sign.init_verify()
- }
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
- self.sign.verify(parts, signature)
- }
- }
- impl CredsPub for PublicCreds {
- fn public_sign(&self) -> &AsymKey<Public, Sign> {
- &self.sign
- }
- }
- impl PartialEq for PublicCreds {
- fn eq(&self, other: &Self) -> bool {
- self.principal() == other.principal()
- }
- }
- #[derive(Clone)]
- pub struct ConcreteCreds {
- sign: AsymKeyPair<Sign>,
- encrypt: AsymKeyPair<Encrypt>,
- writecap: Option<Writecap>,
- }
- impl ConcreteCreds {
- pub fn new(sign: AsymKeyPair<Sign>, encrypt: AsymKeyPair<Encrypt>) -> ConcreteCreds {
- ConcreteCreds {
- sign,
- encrypt,
- writecap: None,
- }
- }
- #[cfg(test)]
- pub fn generate() -> Result<ConcreteCreds> {
- let encrypt = Encrypt::RSA_OAEP_3072_SHA_256.generate()?;
- let sign = Sign::RSA_PSS_3072_SHA_256.generate()?;
- Ok(ConcreteCreds {
- sign,
- encrypt,
- writecap: None,
- })
- }
- pub fn set_writecap(&mut self, writecap: Writecap) {
- self.writecap = Some(writecap)
- }
- }
- impl Verifier for ConcreteCreds {
- type Op<'v> = OsslVerifyOp<'v>;
- fn init_verify(&self) -> Result<Self::Op<'_>> {
- self.sign.init_verify()
- }
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
- self.sign.verify(parts, signature)
- }
- }
- impl Encrypter for ConcreteCreds {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- self.encrypt.encrypt(slice)
- }
- }
- impl Principaled for ConcreteCreds {
- fn principal_of_kind(&self, kind: HashKind) -> Principal {
- self.sign.principal_of_kind(kind)
- }
- }
- impl CredsPub for ConcreteCreds {
- fn public_sign(&self) -> &AsymKey<Public, Sign> {
- &self.sign.public
- }
- }
- impl Signer for ConcreteCreds {
- type Op<'s> = <AsymKeyPair<Sign> as Signer>::Op<'s>;
- fn init_sign(&self) -> Result<Self::Op<'_>> {
- self.sign.init_sign()
- }
- fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
- self.sign.sign(parts)
- }
- }
- impl Decrypter for ConcreteCreds {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- self.encrypt.decrypt(slice)
- }
- }
- impl CredsPriv for ConcreteCreds {
- fn writecap(&self) -> Option<&Writecap> {
- self.writecap.as_ref()
- }
- }
- impl Creds for ConcreteCreds {}
- pub trait Encrypter {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
- }
- impl<T: Encrypter> Encrypter for &T {
- fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- (*self).encrypt(slice)
- }
- }
- pub trait EncrypterExt: Encrypter {
-
-
- fn ser_encrypt<T: Serialize>(&self, value: &T) -> Result<Ciphertext<T>> {
- let data = to_vec(value)?;
- let data = self.encrypt(&data)?;
- Ok(Ciphertext::new(data))
- }
- }
- impl<T: Encrypter + ?Sized> EncrypterExt for T {}
- pub trait Decrypter {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
- }
- impl<T: Decrypter> Decrypter for &T {
- fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
- (*self).decrypt(slice)
- }
- }
- pub trait DecrypterExt: Decrypter {
- fn ser_decrypt<T: DeserializeOwned>(&self, ct: &Ciphertext<T>) -> Result<T> {
- let pt = self.decrypt(ct.data.as_slice())?;
- Ok(from_vec(&pt)?)
- }
- }
- impl<T: Decrypter + ?Sized> DecrypterExt for T {}
- pub trait SignOp: Op {
-
- fn scheme(&self) -> Sign;
-
- fn finish(self) -> Result<Signature> {
- let scheme = self.scheme();
- let mut sig = Signature::empty(scheme);
- self.finish_into(sig.as_mut())?;
- Ok(sig)
- }
- }
- pub struct OsslSignOp<'a> {
- signer: OsslSigner<'a>,
- scheme: Sign,
- }
- impl<'a> Op for OsslSignOp<'a> {
- type Arg = (Sign, &'a PKeyRef<Private>);
- fn init(arg: Self::Arg) -> Result<Self> {
- let scheme = arg.0;
- let mut signer = OsslSigner::new(arg.0.message_digest(), arg.1)?;
- if let Some(padding) = scheme.padding() {
- signer.set_rsa_padding(padding)?;
- }
- Ok(OsslSignOp { signer, scheme })
- }
- fn update(&mut self, data: &[u8]) -> Result<()> {
- Ok(self.signer.update(data)?)
- }
- fn finish_into(self, buf: &mut [u8]) -> Result<usize> {
- Ok(self.signer.sign(buf)?)
- }
- }
- impl<'a> SignOp for OsslSignOp<'a> {
- fn scheme(&self) -> Sign {
- self.scheme
- }
- }
- pub struct SignWrite<T, Op> {
- inner: T,
- op: Op,
- }
- impl<T, Op: SignOp> SignWrite<T, Op> {
- pub fn new(inner: T, op: Op) -> Self {
- SignWrite { inner, op }
- }
- pub fn finish_into(self, buf: &mut [u8]) -> Result<(usize, T)> {
- Ok((self.op.finish_into(buf)?, self.inner))
- }
- pub fn finish(self) -> Result<(Signature, T)> {
- Ok((self.op.finish()?, self.inner))
- }
- }
- impl<T: Write, Op: SignOp> Write for SignWrite<T, Op> {
- fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
- self.op.update(buf)?;
- self.inner.write(buf)
- }
- fn flush(&mut self) -> io::Result<()> {
- self.inner.flush()
- }
- }
- pub trait Signer {
- type Op<'s>: SignOp
- where
- Self: 's;
-
- fn init_sign(&self) -> Result<Self::Op<'_>>;
- fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature>;
- fn ser_sign<T: Serialize>(&self, value: &T) -> Result<Signed<T>> {
- let data = to_vec(value)?;
- let sig = self.sign(std::iter::once(data.as_slice()))?;
- Ok(Signed::new(data, sig))
- }
- fn sign_writecap(&self, writecap: &mut Writecap) -> Result<()> {
- let signed = self.ser_sign(&writecap.body)?;
- writecap.signature = signed.sig;
- Ok(())
- }
- fn ser_sign_into<T: Serialize>(&self, value: &T, buf: &mut Vec<u8>) -> Result<Signature> {
- write_to(value, buf)?;
- self.sign(std::iter::once(buf.as_slice()))
- }
- }
- impl<T: Signer> Signer for &T {
- type Op<'s> = T::Op<'s> where Self: 's;
- fn init_sign(&self) -> Result<Self::Op<'_>> {
- (*self).init_sign()
- }
- fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
- (*self).sign(parts)
- }
- }
- pub trait VerifyOp: Sized {
- type Arg;
- fn init(arg: Self::Arg) -> Result<Self>;
- fn update(&mut self, data: &[u8]) -> Result<()>;
- fn finish(self, sig: &[u8]) -> Result<()>;
- fn scheme(&self) -> Sign;
- }
- pub struct OsslVerifyOp<'a> {
- verifier: OsslVerifier<'a>,
- scheme: Sign,
- }
- impl<'a> VerifyOp for OsslVerifyOp<'a> {
- type Arg = (Sign, &'a PKeyRef<Public>);
- fn init(arg: Self::Arg) -> Result<Self> {
- let scheme = arg.0;
- let mut verifier = OsslVerifier::new(scheme.message_digest(), arg.1)?;
- if let Some(padding) = scheme.padding() {
- verifier.set_rsa_padding(padding)?;
- }
- Ok(OsslVerifyOp { verifier, scheme })
- }
- fn update(&mut self, data: &[u8]) -> Result<()> {
- Ok(self.verifier.update(data)?)
- }
- fn finish(self, sig: &[u8]) -> Result<()> {
- match self.verifier.verify(sig) {
- Ok(true) => Ok(()),
- Ok(false) => Err(Error::InvalidSignature),
- Err(err) => Err(err.into()),
- }
- }
- fn scheme(&self) -> Sign {
- self.scheme
- }
- }
- pub struct VerifyRead<T, Op> {
- inner: T,
- op: Op,
- update_failed: bool,
- }
- impl<T: Read, Op: VerifyOp> VerifyRead<T, Op> {
- pub fn new(inner: T, op: Op) -> Self {
- VerifyRead {
- inner,
- op,
- update_failed: false,
- }
- }
- pub fn finish(self, sig: &[u8]) -> std::result::Result<T, (T, Error)> {
- if self.update_failed {
- return Err((
- self.inner,
- Error::custom("VerifyRead::finish: update_failed was true"),
- ));
- }
- match self.op.finish(sig) {
- Ok(_) => Ok(self.inner),
- Err(err) => Err((self.inner, err)),
- }
- }
- }
- impl<T: Read, Op: VerifyOp> Read for VerifyRead<T, Op> {
- fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
- if self.update_failed {
- return Err(Error::custom("VerifyRead::read update previously failed").into());
- }
- let read = self.inner.read(buf)?;
- if read > 0 {
- if let Err(err) = self.op.update(&buf[..read]) {
- self.update_failed = true;
- error!("VerifyRead::read failed to update VerifyOp: {err}");
- }
- }
- Ok(read)
- }
- }
- pub trait Verifier {
- type Op<'v>: VerifyOp
- where
- Self: 'v;
- fn init_verify(&self) -> Result<Self::Op<'_>>;
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()>;
- fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()> {
- let data = to_vec(value)?;
- self.verify(std::iter::once(data.as_slice()), signature)
- }
- }
- impl<T: Verifier> Verifier for &T {
- type Op<'v> = T::Op<'v> where Self: 'v;
- fn init_verify(&self) -> Result<Self::Op<'_>> {
- (*self).init_verify()
- }
- fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
- (*self).verify(parts, signature)
- }
- }
- pub trait CredsPub: Verifier + Encrypter + Principaled {
-
- fn public_sign(&self) -> &AsymKey<Public, Sign>;
- }
- impl<T: CredsPub> CredsPub for &T {
- fn public_sign(&self) -> &AsymKey<Public, Sign> {
- (*self).public_sign()
- }
- }
- pub trait CredsPriv: Decrypter + Signer {
-
-
- fn writecap(&self) -> Option<&Writecap>;
- }
- impl<T: CredsPriv> CredsPriv for &T {
- fn writecap(&self) -> Option<&Writecap> {
- (*self).writecap()
- }
- }
- pub trait Creds: CredsPriv + CredsPub + Clone {
- fn issue_writecap(
- &self,
- issued_to: Principal,
- path_components: Vec<String>,
- expires: Epoch,
- ) -> Result<Writecap> {
- let path = BlockPath::new(self.principal(), path_components);
- let body = WritecapBody {
- issued_to,
- path,
- expires,
- signing_key: self.public_sign().to_owned(),
- };
- let signed = self.ser_sign(&body)?;
- Ok(Writecap {
- body,
- signature: signed.sig,
- next: self.writecap().map(|e| Box::new(e.to_owned())),
- })
- }
- }
- impl<C: Creds> Creds for &C {
- fn issue_writecap(
- &self,
- issued_to: Principal,
- path_components: Vec<String>,
- expires: Epoch,
- ) -> Result<Writecap> {
- (*self).issue_writecap(issued_to, path_components, expires)
- }
- }
- pub trait CredStore {
- type CredHandle: Creds;
- type ExportedCreds: Serialize + for<'de> Deserialize<'de>;
-
-
- fn node_creds(&self) -> Result<Self::CredHandle>;
-
-
- fn root_creds(&self, password: &str) -> Result<Self::CredHandle>;
-
-
- fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle>;
- fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>>;
- fn export_root_creds(
- &self,
- root_creds: &Self::CredHandle,
- password: &str,
- new_parent: &AsymKeyPub<Encrypt>,
- ) -> Result<Self::ExportedCreds>;
- fn import_root_creds(
- &self,
- password: &str,
- exported: Self::ExportedCreds,
- ) -> Result<Self::CredHandle>;
- fn assign_node_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
- -> Result<()>;
- }
- impl BlockMeta {
-
-
-
- pub fn assert_valid(&self, path: &BlockPath) -> Result<()> {
- let body = &self.body;
- let writecap = body
- .writecap
- .as_ref()
- .ok_or(crate::Error::MissingWritecap)?;
- writecap.assert_valid_for(path)?;
- let signed_by = body.signing_key.principal();
- if writecap.body.issued_to != signed_by {
- return Err(Error::signature_mismatch(
- writecap.body.issued_to.clone(),
- signed_by,
- ));
- }
- body.signing_key.ser_verify(&body, self.sig.as_slice())
- }
- }
- #[derive(Debug, PartialEq, Eq, Display)]
- pub enum WritecapAuthzErr {
-
- UnauthorizedPath,
-
- Expired,
-
- NotChained,
-
- RootDoesNotOwnPath,
-
- Serde(String),
-
-
- ChainTooLong(usize),
- }
- impl Writecap {
-
- pub fn assert_valid_for(&self, path: &BlockPath) -> Result<()> {
- let mut writecap = self;
- const CHAIN_LEN_LIMIT: usize = 256;
- let mut prev: Option<&Writecap> = None;
- let mut sig_input_buf = Vec::new();
- let now = Epoch::now();
- for _ in 0..CHAIN_LEN_LIMIT {
- if !writecap.body.path.contains(path) {
- return Err(WritecapAuthzErr::UnauthorizedPath.into());
- }
- if writecap.body.expires <= now {
- return Err(WritecapAuthzErr::Expired.into());
- }
- if let Some(prev) = &prev {
- if prev
- .body
- .signing_key
- .principal_of_kind(writecap.body.issued_to.kind())
- != writecap.body.issued_to
- {
- return Err(WritecapAuthzErr::NotChained.into());
- }
- }
- sig_input_buf.clear();
- write_to(&writecap.body, &mut sig_input_buf)
- .map_err(|e| WritecapAuthzErr::Serde(e.to_string()))?;
- writecap.body.signing_key.verify(
- std::iter::once(sig_input_buf.as_slice()),
- writecap.signature.as_slice(),
- )?;
- match &writecap.next {
- Some(next) => {
- prev = Some(writecap);
- writecap = next;
- }
- None => {
-
-
- if writecap
- .body
- .signing_key
- .principal_of_kind(path.root().kind())
- == *path.root()
- {
- return Ok(());
- } else {
- return Err(WritecapAuthzErr::RootDoesNotOwnPath.into());
- }
- }
- }
- }
- Err(WritecapAuthzErr::ChainTooLong(CHAIN_LEN_LIMIT).into())
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- use crate::{
- crypto::secret_stream::SecretStream,
- test_helpers::{self, *},
- BrotliParams, Sectored, SectoredBuf, TryCompose,
- };
- use std::{
- io::{Seek, SeekFrom},
- time::Duration,
- };
- #[test]
- fn encrypt_decrypt_block() {
- const SECT_SZ: usize = 16;
- const SECT_CT: usize = 8;
- let creds = make_key_pair();
- let mut block = make_block_with(&creds);
- write_fill(&mut block, SECT_SZ, SECT_CT);
- block.seek(SeekFrom::Start(0)).expect("seek failed");
- read_check(block, SECT_SZ, SECT_CT);
- }
- #[test]
- fn rsa_sign_and_verify() -> Result<()> {
- let key = make_key_pair();
- let header = b"About: lyrics".as_slice();
- let message = b"Everything that feels so good is bad bad bad.".as_slice();
- let signature = key.sign([header, message].into_iter())?;
- key.verify([header, message].into_iter(), signature.as_slice())
- }
- #[test]
- fn hash_to_string() {
- let hash = make_principal().0;
- let string = hash.to_string();
- assert_eq!("0!dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
- }
- #[test]
- fn hash_to_string_round_trip() -> Result<()> {
- let expected = make_principal().0;
- let string = expected.to_string();
- let actual = VarHash::try_from(string.as_str())?;
- assert_eq!(expected, actual);
- Ok(())
- }
- #[test]
- fn verify_writecap_valid() {
- let writecap = make_writecap(vec!["apps", "verse"]);
- writecap
- .assert_valid_for(&writecap.body.path)
- .expect("failed to verify writecap");
- }
- #[test]
- fn verify_writecap_invalid_signature() -> Result<()> {
- let mut writecap = make_writecap(vec!["apps", "verse"]);
- writecap.signature = Signature::empty(Sign::RSA_PSS_3072_SHA_256);
- let result = writecap.assert_valid_for(&writecap.body.path);
- if let Err(Error::InvalidSignature) = result {
- Ok(())
- } else {
- Err(Error::custom(format!("unexpected result {:?}", result)))
- }
- }
- fn assert_authz_err<T: std::fmt::Debug>(
- expected: WritecapAuthzErr,
- result: Result<T>,
- ) -> Result<()> {
- if let Err(Error::WritecapAuthzErr(actual)) = &result {
- if *actual == expected {
- return Ok(());
- }
- }
- Err(Error::custom(format!("unexpected result: {:?}", result)))
- }
- #[test]
- fn verify_writecap_invalid_path_not_contained() -> Result<()> {
- let writecap = make_writecap(vec!["apps", "verse"]);
- let mut path = writecap.body.path.clone();
- path.pop_component();
-
-
- let result = writecap.assert_valid_for(&path);
- assert_authz_err(WritecapAuthzErr::UnauthorizedPath, result)
- }
- #[test]
- fn verify_writecap_invalid_expired() -> Result<()> {
- let mut writecap = make_writecap(vec!["apps", "verse"]);
- writecap.body.expires = Epoch::now() - Duration::from_secs(1);
- let result = writecap.assert_valid_for(&writecap.body.path);
- assert_authz_err(WritecapAuthzErr::Expired, result)
- }
- #[test]
- fn verify_writecap_invalid_not_chained() -> Result<()> {
- let (mut root_writecap, root_key) = make_self_signed_writecap();
- root_writecap.body.issued_to = Principal(VarHash::from(HashKind::Sha2_256));
- root_key.sign_writecap(&mut root_writecap)?;
- let node_principal = NODE_CREDS.principal();
- let writecap = make_writecap_trusted_by(
- root_writecap,
- &root_key,
- node_principal,
- vec!["apps", "contacts"],
- );
- let result = writecap.assert_valid_for(&writecap.body.path);
- assert_authz_err(WritecapAuthzErr::NotChained, result)
- }
- #[test]
- fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
- let (mut root_writecap, root_key) = make_self_signed_writecap();
- let owner = Principal(VarHash::from(HashKind::Sha2_256));
- root_writecap.body.path = make_path_with_root(owner, vec![]);
- root_key.sign_writecap(&mut root_writecap)?;
- let node_principal = NODE_CREDS.principal();
- let writecap = make_writecap_trusted_by(
- root_writecap,
- &root_key,
- node_principal,
- vec!["apps", "contacts"],
- );
- let result = writecap.assert_valid_for(&writecap.body.path);
- assert_authz_err(WritecapAuthzErr::RootDoesNotOwnPath, result)
- }
- #[test]
- fn aeadkey_encrypt_decrypt_aes256gcm() {
- let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
- let aad = [1u8; 16];
- let expected = [2u8; 32];
- let tagged = key.encrypt(aad, &expected).expect("encrypt failed");
- let actual = key.decrypt(&tagged).expect("decrypt failed");
- assert_eq!(expected, actual.as_slice());
- }
- #[test]
- fn aeadkey_decrypt_fails_when_ct_modified() {
- let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
- let aad = [1u8; 16];
- let expected = [2u8; 32];
- let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
- tagged.ciphertext.data[0] = tagged.ciphertext.data[0].wrapping_add(1);
- let result = key.decrypt(&tagged);
- assert!(result.is_err())
- }
- #[test]
- fn aeadkey_decrypt_fails_when_aad_modified() {
- let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
- let aad = [1u8; 16];
- let expected = [2u8; 32];
- let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
- tagged.aad[0] = tagged.aad[0].wrapping_add(1);
- let result = key.decrypt(&tagged);
- assert!(result.is_err())
- }
- #[test]
- fn compose_merkle_and_secret_streams() {
- use merkle_stream::tests::make_merkle_stream_filled_with_zeros;
- const SECT_SZ: usize = 4096;
- const SECT_CT: usize = 16;
- let merkle = make_merkle_stream_filled_with_zeros(SECT_SZ, SECT_CT);
- let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
- let mut secret = SecretStream::new(key)
- .try_compose(merkle)
- .expect("compose for secret failed");
- let secret_sect_sz = secret.sector_sz();
- write_fill(&mut secret, secret_sect_sz, SECT_CT);
- secret.seek(SeekFrom::Start(0)).expect("seek failed");
- read_check(&mut secret, secret_sect_sz, SECT_CT);
- }
- #[test]
- fn compress_then_encrypt() {
- use brotli::{CompressorWriter, Decompressor};
- const SECT_SZ: usize = 4096;
- const SECT_CT: usize = 16;
- let params = BrotliParams::new(SECT_SZ, 8, 20);
- let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
- let mut inner = SectoredBuf::new()
- .try_compose(
- SecretStream::new(key)
- .try_compose(SectoredCursor::new(Vec::new(), SECT_SZ))
- .expect("compose for inner failed"),
- )
- .expect("compose with sectored buffer failed");
- {
- let write: CompressorWriter<_> = params
- .clone()
- .try_compose(&mut inner)
- .expect("compose for write failed");
- write_fill(write, SECT_SZ, SECT_CT);
- }
- inner.seek(SeekFrom::Start(0)).expect("seek failed");
- {
- let read: Decompressor<_> = params
- .try_compose(&mut inner)
- .expect("compose for read failed");
- read_check(read, SECT_SZ, SECT_CT);
- }
- }
- fn ossl_hash_op_same_as_digest_test_case<H: Hash + From<DigestBytes>>(kind: HashKind) {
- let parts = (0u8..32).map(|k| vec![k; kind.len()]).collect::<Vec<_>>();
- let expected = {
- let mut expected = vec![0u8; kind.len()];
- kind.digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
- .unwrap();
- expected
- };
- let mut op = OsslHashOp::<H>::init(kind).unwrap();
- for part in parts.iter() {
- op.update(part.as_slice()).unwrap();
- }
- let actual = op.finish().unwrap();
- assert_eq!(expected.as_slice(), actual.as_ref());
- }
-
-
- #[test]
- fn ossl_hash_op_same_as_digest() {
- ossl_hash_op_same_as_digest_test_case::<Sha2_256>(Sha2_256::KIND);
- ossl_hash_op_same_as_digest_test_case::<Sha2_512>(Sha2_512::KIND);
- }
-
- #[test]
- fn hash_stream_agrees_with_digest_method() {
- let cursor = BtCursor::new([0u8; 3 * 32]);
- let parts = (1u8..4).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
- let expected = {
- let mut expected = Sha2_512::default();
- HashKind::Sha2_512
- .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
- .unwrap();
- expected
- };
- let op = OsslHashOp::<Sha2_512>::init(Sha2_512::KIND).unwrap();
- let mut wrap = HashStream::new(cursor, op);
- for part in parts.iter() {
- wrap.write(part.as_slice()).unwrap();
- }
- let actual = wrap.finish().unwrap();
- assert_eq!(expected, actual);
- }
-
-
- #[test]
- fn var_hash_op_agress_with_digest_method() {
- let parts = (32..64u8).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
- let expected = {
- let mut expected = VarHash::from(HashKind::Sha2_512);
- HashKind::Sha2_512
- .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
- .unwrap();
- expected
- };
- let mut op = VarHashOp::init(HashKind::Sha2_512).unwrap();
- for part in parts.iter() {
- op.update(part.as_slice()).unwrap();
- }
- let actual = op.finish().unwrap();
- assert_eq!(expected, actual);
- }
-
- #[test]
- fn ossl_sign_op_sig_can_be_verified() {
- let keys = &test_helpers::NODE_CREDS;
- let part_values = (1..9u8).map(|k| [k; 32]).collect::<Vec<_>>();
- let get_parts = || part_values.iter().map(|a| a.as_slice());
- let mut sign_op = keys.init_sign().expect("init_sign failed");
- for part in get_parts() {
- sign_op.update(part).expect("update failed");
- }
- let sig = sign_op.finish().expect("finish failed");
- keys.verify(get_parts(), sig.as_ref())
- .expect("verify failed");
- }
-
- #[test]
- fn sign_write_sig_can_be_verified() {
- use crate::Decompose;
- const LEN: usize = 512;
- let cursor = BtCursor::new([0u8; LEN]);
- let keys = &test_helpers::NODE_CREDS;
- let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
- let mut sign_write = SignWrite::new(cursor, sign_op);
- for part in (1..9u8).map(|k| [k; LEN / 8]) {
- sign_write.write(part.as_slice()).expect("write failed");
- }
- let (sig, cursor) = sign_write.finish().expect("finish failed");
- let array = cursor.into_inner();
- keys.verify(std::iter::once(array.as_slice()), sig.as_ref())
- .expect("verify failed");
- }
-
- #[test]
- fn sign_write_then_verify_read() {
- const LEN: usize = 512;
- let cursor = BtCursor::new([0u8; LEN]);
- let keys = &test_helpers::NODE_CREDS;
- let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
- let mut sign_write = SignWrite::new(cursor, sign_op);
- for part in (1..9u8).map(|k| [k; LEN / 8]) {
- sign_write.write(part.as_slice()).expect("write failed");
- }
- let (sig, mut cursor) = sign_write.finish().expect("finish failed");
- cursor.seek(SeekFrom::Start(0)).expect("seek failed");
- let verify_op = keys.sign.public.init_verify().expect("init_verify failed");
- let mut verify_read = VerifyRead::new(cursor, verify_op);
- let mut buf = Vec::with_capacity(LEN);
- verify_read
- .read_to_end(&mut buf)
- .expect("read_to_end failed");
- verify_read
- .finish(sig.as_ref())
- .expect("failed to verify signature");
- }
-
- mod dependency_tests {
- use super::*;
- use openssl::{
- ec::{EcGroup, EcKey},
- nid::Nid,
- };
-
- #[test]
- fn aes_256_cbc_roundtrip() {
- use super::*;
- let expected = b"We attack at the crack of noon!";
- let cipher = Cipher::aes_256_cbc();
- let key = BLOCK_KEY.key_slice();
- let iv = BLOCK_KEY.iv_slice();
- let ciphertext = openssl_encrypt(cipher, key, iv, expected).unwrap();
- let actual = openssl_decrypt(cipher, key, iv, ciphertext.as_slice()).unwrap();
- assert_eq!(expected, actual.as_slice());
- }
-
- #[test]
- fn secp256k1_key_lengths() {
- let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
- let key = EcKey::generate(&group).unwrap();
- let public = key.public_key_to_der().unwrap();
- let private = key.private_key_to_der().unwrap();
- let public_len = public.len();
- let private_len = private.len();
- assert_eq!(88, public_len);
- assert_eq!(118, private_len);
- }
- #[test]
- fn ed25519_key_lengths() {
- let key = PKey::generate_x25519().unwrap();
- let public = key.public_key_to_der().unwrap();
- let private = key.private_key_to_der().unwrap();
- let public_len = public.len();
- let private_len = private.len();
- assert_eq!(44, public_len);
- assert_eq!(48, private_len);
- }
- }
- }
|