mod.rs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516
  1. pub mod merkle_stream;
  2. pub mod tpm;
  3. pub use merkle_stream::MerkleStream;
  4. pub mod secret_stream;
  5. pub use secret_stream::SecretStream;
  6. use crate::{
  7. fmt, io, BigArray, BlockMeta, BlockPath, Deserialize, Epoch, Formatter, Hashable, Principal,
  8. Principaled, Serialize, Writecap, WritecapBody,
  9. };
  10. use btserde::{self, from_vec, to_vec, write_to};
  11. use foreign_types::ForeignType;
  12. use log::error;
  13. use openssl::{
  14. encrypt::{Decrypter as OsslDecrypter, Encrypter as OsslEncrypter},
  15. error::ErrorStack,
  16. hash::{hash, DigestBytes, Hasher, MessageDigest},
  17. nid::Nid,
  18. pkey::{HasPrivate, HasPublic, PKey, PKeyRef},
  19. rand::rand_bytes,
  20. rsa::{Padding as OpensslPadding, Rsa as OsslRsa},
  21. sign::{Signer as OsslSigner, Verifier as OsslVerifier},
  22. symm::{decrypt as openssl_decrypt, encrypt as openssl_encrypt, Cipher, Crypter, Mode},
  23. };
  24. use serde::{
  25. de::{self, DeserializeOwned, Deserializer, SeqAccess, Visitor},
  26. ser::{SerializeStruct, Serializer},
  27. };
  28. use std::{
  29. fmt::Display,
  30. io::{Read, Write},
  31. marker::PhantomData,
  32. num::TryFromIntError,
  33. };
  34. use strum_macros::{Display, EnumDiscriminants, FromRepr};
  35. use zeroize::ZeroizeOnDrop;
  36. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone)]
  37. pub struct Ciphertext<T> {
  38. data: Vec<u8>,
  39. phantom: PhantomData<T>,
  40. }
  41. impl<T> Ciphertext<T> {
  42. pub fn new(data: Vec<u8>) -> Ciphertext<T> {
  43. Ciphertext {
  44. data,
  45. phantom: PhantomData,
  46. }
  47. }
  48. }
  49. pub struct Signed<T> {
  50. _data: Vec<u8>,
  51. sig: Signature,
  52. phantom: PhantomData<T>,
  53. }
  54. impl<T> Signed<T> {
  55. pub fn new(data: Vec<u8>, sig: Signature) -> Signed<T> {
  56. Signed {
  57. _data: data,
  58. sig,
  59. phantom: PhantomData,
  60. }
  61. }
  62. }
  63. /// Errors that can occur during cryptographic operations.
  64. #[derive(Debug)]
  65. pub enum Error {
  66. NoReadCap,
  67. NoKeyAvailable,
  68. MissingPrivateKey,
  69. KeyVariantUnsupported,
  70. BlockNotEncrypted,
  71. InvalidHashFormat,
  72. InvalidSignature,
  73. IncorrectSize { expected: usize, actual: usize },
  74. IndexOutOfBounds { index: usize, limit: usize },
  75. IndivisibleSize { divisor: usize, actual: usize },
  76. InvalidOffset { actual: usize, limit: usize },
  77. HashCmpFailure,
  78. RootHashNotVerified,
  79. SignatureMismatch(Box<SignatureMismatch>),
  80. WritecapAuthzErr(WritecapAuthzErr),
  81. Serde(btserde::Error),
  82. Io(std::io::Error),
  83. Custom(Box<dyn std::fmt::Debug + Send + Sync>),
  84. }
  85. impl Error {
  86. pub(crate) fn custom<E: std::fmt::Debug + Send + Sync + 'static>(err: E) -> Error {
  87. Error::Custom(Box::new(err))
  88. }
  89. fn signature_mismatch(expected: Principal, actual: Principal) -> Error {
  90. Error::SignatureMismatch(Box::new(SignatureMismatch { expected, actual }))
  91. }
  92. }
  93. impl Display for Error {
  94. fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
  95. match self {
  96. Error::NoReadCap => write!(f, "no readcap"),
  97. Error::NoKeyAvailable => write!(f, "no key available"),
  98. Error::MissingPrivateKey => write!(f, "private key was missing"),
  99. Error::KeyVariantUnsupported => write!(f, "unsupported key variant"),
  100. Error::BlockNotEncrypted => write!(f, "block was not encrypted"),
  101. Error::InvalidHashFormat => write!(f, "invalid format"),
  102. Error::InvalidSignature => write!(f, "invalid signature"),
  103. Error::IncorrectSize { expected, actual } => {
  104. write!(f, "expected size {expected} but got {actual}")
  105. }
  106. Error::IndexOutOfBounds { index, limit } => write!(
  107. f,
  108. "index {} is out of bounds, it must be strictly less than {}",
  109. index, limit
  110. ),
  111. Error::IndivisibleSize { divisor, actual } => write!(
  112. f,
  113. "expected a size which is divisible by {} but got {}",
  114. divisor, actual
  115. ),
  116. Error::InvalidOffset { actual, limit } => write!(
  117. f,
  118. "offset {} is out of bounds, it must be strictly less than {}",
  119. actual, limit
  120. ),
  121. Error::HashCmpFailure => write!(f, "hash data are not equal"),
  122. Error::RootHashNotVerified => write!(f, "root hash is not verified"),
  123. Error::SignatureMismatch(mismatch) => {
  124. let actual = &mismatch.actual;
  125. let expected = &mismatch.expected;
  126. write!(
  127. f,
  128. "expected a signature from {expected} but found one from {actual}"
  129. )
  130. }
  131. Error::WritecapAuthzErr(err) => err.fmt(f),
  132. Error::Serde(err) => err.fmt(f),
  133. Error::Io(err) => err.fmt(f),
  134. Error::Custom(cus) => cus.fmt(f),
  135. }
  136. }
  137. }
  138. impl std::error::Error for Error {}
  139. impl From<WritecapAuthzErr> for Error {
  140. fn from(err: WritecapAuthzErr) -> Self {
  141. Error::WritecapAuthzErr(err)
  142. }
  143. }
  144. impl From<ErrorStack> for Error {
  145. fn from(error: ErrorStack) -> Error {
  146. Error::custom(error)
  147. }
  148. }
  149. impl From<btserde::Error> for Error {
  150. fn from(error: btserde::Error) -> Error {
  151. Error::Serde(error)
  152. }
  153. }
  154. impl From<std::io::Error> for Error {
  155. fn from(error: std::io::Error) -> Error {
  156. Error::Io(error)
  157. }
  158. }
  159. impl From<TryFromIntError> for Error {
  160. fn from(err: TryFromIntError) -> Self {
  161. Error::custom(err)
  162. }
  163. }
  164. impl From<Error> for io::Error {
  165. fn from(err: Error) -> Self {
  166. io::Error::new(io::ErrorKind::Other, err)
  167. }
  168. }
  169. impl From<crate::Error> for Error {
  170. fn from(err: crate::Error) -> Self {
  171. Error::custom(err)
  172. }
  173. }
  174. pub(crate) type Result<T> = std::result::Result<T, Error>;
  175. #[derive(Debug)]
  176. pub struct SignatureMismatch {
  177. pub actual: Principal,
  178. pub expected: Principal,
  179. }
  180. /// Returns an array of the given length filled with cryptographically strong random data.
  181. pub fn rand_array<const LEN: usize>() -> Result<[u8; LEN]> {
  182. let mut array = [0; LEN];
  183. rand_bytes(&mut array)?;
  184. Ok(array)
  185. }
  186. /// Returns a vector of the given length with with cryptographically strong random data.
  187. pub fn rand_vec(len: usize) -> Result<Vec<u8>> {
  188. let mut vec = vec![0; len];
  189. rand_bytes(&mut vec)?;
  190. Ok(vec)
  191. }
  192. /// An ongoing Init-Update-Finish operation.
  193. pub trait Op: Sized {
  194. /// The type of the argument given to `init`.
  195. type Arg;
  196. /// Initialize a new operation.
  197. fn init(arg: Self::Arg) -> Result<Self>;
  198. /// Update this operation using the given data.
  199. fn update(&mut self, data: &[u8]) -> Result<()>;
  200. /// Finish this operation and write the result into the given buffer. If the given buffer is not
  201. /// large enough the implementation must return Error::IncorrectSize.
  202. fn finish_into(self, buf: &mut [u8]) -> Result<usize>;
  203. }
  204. /// An ongoing hash hash operation.
  205. pub trait HashOp: Op {
  206. /// The specific hash type which is returned by the finish method.
  207. type Hash: Hash;
  208. /// Returns the kind of hash this operation is computing.
  209. fn kind(&self) -> HashKind;
  210. /// Finish this operation and return a hash type containing the result.
  211. fn finish(self) -> Result<Self::Hash>;
  212. }
  213. // A hash operation which uses OpenSSL.
  214. pub struct OsslHashOp<H> {
  215. hasher: Hasher,
  216. phantom: PhantomData<H>,
  217. kind: HashKind,
  218. }
  219. impl<H> Op for OsslHashOp<H> {
  220. type Arg = HashKind;
  221. fn init(arg: Self::Arg) -> Result<Self> {
  222. let hasher = Hasher::new(arg.into())?;
  223. let phantom = PhantomData;
  224. Ok(OsslHashOp {
  225. hasher,
  226. phantom,
  227. kind: arg,
  228. })
  229. }
  230. fn update(&mut self, data: &[u8]) -> Result<()> {
  231. Ok(self.hasher.update(data)?)
  232. }
  233. fn finish_into(mut self, buf: &mut [u8]) -> Result<usize> {
  234. if buf.len() < self.kind.len() {
  235. return Err(Error::IncorrectSize {
  236. expected: self.kind.len(),
  237. actual: buf.len(),
  238. });
  239. }
  240. let digest = self.hasher.finish()?;
  241. let slice = digest.as_ref();
  242. buf.copy_from_slice(slice);
  243. Ok(slice.len())
  244. }
  245. }
  246. impl<H: Hash + From<DigestBytes>> HashOp for OsslHashOp<H> {
  247. type Hash = H;
  248. fn kind(&self) -> HashKind {
  249. self.kind
  250. }
  251. fn finish(mut self) -> Result<Self::Hash> {
  252. let digest = self.hasher.finish()?;
  253. Ok(H::from(digest))
  254. }
  255. }
  256. /// A wrapper which updates a `HashOp` when data is read or written.
  257. pub struct HashStream<T, Op: HashOp> {
  258. inner: T,
  259. op: Op,
  260. update_failed: bool,
  261. }
  262. impl<T, Op: HashOp> HashStream<T, Op> {
  263. /// Create a new `HashWrap`.
  264. pub fn new(inner: T, op: Op) -> HashStream<T, Op> {
  265. HashStream {
  266. inner,
  267. op,
  268. update_failed: false,
  269. }
  270. }
  271. /// Finish this hash operation and write the result into the given buffer. The number of bytes
  272. /// written is returned.
  273. pub fn finish_into(self, buf: &mut [u8]) -> Result<usize> {
  274. if self.update_failed {
  275. return Err(Error::custom(
  276. "HashStream::finish_into can't produce result due to HashOp update failure",
  277. ));
  278. }
  279. self.op.finish_into(buf)
  280. }
  281. /// Finish this hash operation and return the resulting hash.
  282. pub fn finish(self) -> Result<Op::Hash> {
  283. if self.update_failed {
  284. return Err(Error::custom(
  285. "HashStream::finish can't produce result due to HashOp update failure",
  286. ));
  287. }
  288. self.op.finish()
  289. }
  290. }
  291. impl<T: Read, Op: HashOp> Read for HashStream<T, Op> {
  292. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  293. if self.update_failed {
  294. return Err(Error::custom(
  295. "HashStream::read can't continue due to previous HashOp update failure",
  296. )
  297. .into());
  298. }
  299. let read = self.inner.read(buf)?;
  300. if read > 0 {
  301. if let Err(err) = self.op.update(&buf[..read]) {
  302. self.update_failed = true;
  303. error!("HashWrap::read failed to update HashOp: {}", err);
  304. }
  305. }
  306. Ok(read)
  307. }
  308. }
  309. impl<T: Write, Op: HashOp> Write for HashStream<T, Op> {
  310. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  311. self.op.update(buf)?;
  312. self.inner.write(buf)
  313. }
  314. fn flush(&mut self) -> io::Result<()> {
  315. self.inner.flush()
  316. }
  317. }
  318. /// A cryptographic hash.
  319. pub trait Hash: AsRef<[u8]> + AsMut<[u8]> + Sized {
  320. /// The hash operation associated with this `Hash`.
  321. type Op: HashOp;
  322. /// The type of the argument required by `new`.
  323. type Arg;
  324. /// Returns a new `Hash` instance.
  325. fn new(arg: Self::Arg) -> Self;
  326. /// Returns the `HashKind` of self.
  327. fn kind(&self) -> HashKind;
  328. /// Starts a new hash operation.
  329. fn start_op(&self) -> Result<Self::Op>;
  330. }
  331. /// Trait for hash types which can be created with no arguments.
  332. pub trait DefaultHash: Hash {
  333. fn default() -> Self;
  334. }
  335. impl<A: Default, T: Hash<Arg = A>> DefaultHash for T {
  336. fn default() -> Self {
  337. Self::new(A::default())
  338. }
  339. }
  340. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
  341. pub struct Sha2_256([u8; Self::LEN]);
  342. impl Sha2_256 {
  343. pub const KIND: HashKind = HashKind::Sha2_256;
  344. pub const LEN: usize = Self::KIND.len();
  345. }
  346. impl AsRef<[u8]> for Sha2_256 {
  347. fn as_ref(&self) -> &[u8] {
  348. self.0.as_slice()
  349. }
  350. }
  351. impl AsMut<[u8]> for Sha2_256 {
  352. fn as_mut(&mut self) -> &mut [u8] {
  353. self.0.as_mut_slice()
  354. }
  355. }
  356. impl From<DigestBytes> for Sha2_256 {
  357. fn from(value: DigestBytes) -> Self {
  358. let mut hash = Sha2_256::new(());
  359. // TODO: It would be great if there was a way to avoid this copy.
  360. hash.as_mut().copy_from_slice(value.as_ref());
  361. hash
  362. }
  363. }
  364. impl From<[u8; Self::LEN]> for Sha2_256 {
  365. fn from(value: [u8; Self::LEN]) -> Self {
  366. Sha2_256(value)
  367. }
  368. }
  369. impl From<Sha2_256> for [u8; Sha2_256::LEN] {
  370. fn from(value: Sha2_256) -> Self {
  371. value.0
  372. }
  373. }
  374. impl Hash for Sha2_256 {
  375. type Op = OsslHashOp<Sha2_256>;
  376. type Arg = ();
  377. fn new(_: Self::Arg) -> Self {
  378. Sha2_256([0u8; Self::KIND.len()])
  379. }
  380. fn kind(&self) -> HashKind {
  381. Self::KIND
  382. }
  383. fn start_op(&self) -> Result<Self::Op> {
  384. OsslHashOp::init(Self::KIND)
  385. }
  386. }
  387. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hashable, Clone)]
  388. pub struct Sha2_512(#[serde(with = "BigArray")] [u8; Self::LEN]);
  389. impl Sha2_512 {
  390. pub const KIND: HashKind = HashKind::Sha2_512;
  391. pub const LEN: usize = Self::KIND.len();
  392. }
  393. impl AsRef<[u8]> for Sha2_512 {
  394. fn as_ref(&self) -> &[u8] {
  395. self.0.as_slice()
  396. }
  397. }
  398. impl AsMut<[u8]> for Sha2_512 {
  399. fn as_mut(&mut self) -> &mut [u8] {
  400. self.0.as_mut_slice()
  401. }
  402. }
  403. impl From<DigestBytes> for Sha2_512 {
  404. fn from(value: DigestBytes) -> Self {
  405. let mut hash = Sha2_512::new(());
  406. hash.as_mut().copy_from_slice(value.as_ref());
  407. hash
  408. }
  409. }
  410. impl From<[u8; Self::LEN]> for Sha2_512 {
  411. fn from(value: [u8; Self::LEN]) -> Self {
  412. Self(value)
  413. }
  414. }
  415. impl From<Sha2_512> for [u8; Sha2_512::LEN] {
  416. fn from(value: Sha2_512) -> Self {
  417. value.0
  418. }
  419. }
  420. impl Hash for Sha2_512 {
  421. type Op = OsslHashOp<Sha2_512>;
  422. type Arg = ();
  423. fn new(_: Self::Arg) -> Self {
  424. Sha2_512([0u8; Self::LEN])
  425. }
  426. fn kind(&self) -> HashKind {
  427. Self::KIND
  428. }
  429. fn start_op(&self) -> Result<Self::Op> {
  430. OsslHashOp::init(Self::KIND)
  431. }
  432. }
  433. /// One of several concrete hash types.
  434. #[derive(
  435. Debug,
  436. PartialEq,
  437. Eq,
  438. Serialize,
  439. Deserialize,
  440. Hashable,
  441. Clone,
  442. EnumDiscriminants,
  443. PartialOrd,
  444. Ord,
  445. )]
  446. #[strum_discriminants(derive(FromRepr, Display, Serialize, Deserialize))]
  447. #[strum_discriminants(name(HashKind))]
  448. pub enum VarHash {
  449. Sha2_256(Sha2_256),
  450. Sha2_512(Sha2_512),
  451. }
  452. impl Default for HashKind {
  453. fn default() -> HashKind {
  454. HashKind::Sha2_256
  455. }
  456. }
  457. impl Default for VarHash {
  458. fn default() -> Self {
  459. HashKind::default().into()
  460. }
  461. }
  462. impl HashKind {
  463. #[allow(clippy::len_without_is_empty)]
  464. pub const fn len(self) -> usize {
  465. match self {
  466. HashKind::Sha2_256 => 32,
  467. HashKind::Sha2_512 => 64,
  468. }
  469. }
  470. pub fn digest<'a, I: Iterator<Item = &'a [u8]>>(self, dest: &mut [u8], parts: I) -> Result<()> {
  471. if dest.len() != self.len() {
  472. return Err(Error::IncorrectSize {
  473. expected: self.len(),
  474. actual: dest.len(),
  475. });
  476. }
  477. let mut hasher = Hasher::new(self.into())?;
  478. for part in parts {
  479. hasher.update(part)?;
  480. }
  481. let hash = hasher.finish()?;
  482. dest.copy_from_slice(&hash);
  483. Ok(())
  484. }
  485. }
  486. impl TryFrom<MessageDigest> for HashKind {
  487. type Error = Error;
  488. fn try_from(value: MessageDigest) -> Result<Self> {
  489. let nid = value.type_();
  490. if Nid::SHA256 == nid {
  491. Ok(HashKind::Sha2_256)
  492. } else if Nid::SHA512 == nid {
  493. Ok(HashKind::Sha2_512)
  494. } else {
  495. Err(Error::custom(format!(
  496. "Unsupported MessageDigest with NID: {:?}",
  497. nid
  498. )))
  499. }
  500. }
  501. }
  502. impl From<HashKind> for MessageDigest {
  503. fn from(kind: HashKind) -> Self {
  504. match kind {
  505. HashKind::Sha2_256 => MessageDigest::sha256(),
  506. HashKind::Sha2_512 => MessageDigest::sha512(),
  507. }
  508. }
  509. }
  510. impl VarHash {
  511. /// The character that's used to separate a hash type from its value in its string
  512. /// representation.
  513. const HASH_SEP: char = '!';
  514. pub fn kind(&self) -> HashKind {
  515. self.into()
  516. }
  517. pub fn as_slice(&self) -> &[u8] {
  518. self.as_ref()
  519. }
  520. pub fn as_mut_slice(&mut self) -> &mut [u8] {
  521. self.as_mut()
  522. }
  523. }
  524. impl From<HashKind> for VarHash {
  525. fn from(kind: HashKind) -> VarHash {
  526. match kind {
  527. HashKind::Sha2_256 => VarHash::Sha2_256(Sha2_256::default()),
  528. HashKind::Sha2_512 => VarHash::Sha2_512(Sha2_512::default()),
  529. }
  530. }
  531. }
  532. impl AsRef<[u8]> for VarHash {
  533. fn as_ref(&self) -> &[u8] {
  534. match self {
  535. VarHash::Sha2_256(arr) => arr.as_ref(),
  536. VarHash::Sha2_512(arr) => arr.as_ref(),
  537. }
  538. }
  539. }
  540. impl AsMut<[u8]> for VarHash {
  541. fn as_mut(&mut self) -> &mut [u8] {
  542. match self {
  543. VarHash::Sha2_256(arr) => arr.as_mut(),
  544. VarHash::Sha2_512(arr) => arr.as_mut(),
  545. }
  546. }
  547. }
  548. impl TryFrom<MessageDigest> for VarHash {
  549. type Error = Error;
  550. fn try_from(value: MessageDigest) -> Result<Self> {
  551. let kind: HashKind = value.try_into()?;
  552. Ok(kind.into())
  553. }
  554. }
  555. impl Hash for VarHash {
  556. type Op = VarHashOp;
  557. type Arg = HashKind;
  558. fn new(arg: Self::Arg) -> Self {
  559. arg.into()
  560. }
  561. fn kind(&self) -> HashKind {
  562. self.kind()
  563. }
  564. fn start_op(&self) -> Result<Self::Op> {
  565. VarHashOp::init(self.kind())
  566. }
  567. }
  568. impl TryFrom<&str> for VarHash {
  569. type Error = Error;
  570. fn try_from(string: &str) -> Result<VarHash> {
  571. let mut split: Vec<&str> = string.split(Self::HASH_SEP).collect();
  572. if split.len() != 2 {
  573. return Err(Error::InvalidHashFormat);
  574. };
  575. let second = split.pop().ok_or(Error::InvalidHashFormat)?;
  576. let first = split
  577. .pop()
  578. .ok_or(Error::InvalidHashFormat)?
  579. .parse::<usize>()
  580. .map_err(|_| Error::InvalidHashFormat)?;
  581. let mut hash = VarHash::from(HashKind::from_repr(first).ok_or(Error::InvalidHashFormat)?);
  582. base64_url::decode_to_slice(second, hash.as_mut()).map_err(|_| Error::InvalidHashFormat)?;
  583. Ok(hash)
  584. }
  585. }
  586. impl Display for VarHash {
  587. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  588. let hash_kind: HashKind = self.into();
  589. let hash_data = base64_url::encode(self.as_ref());
  590. write!(f, "{}{}{hash_data}", hash_kind as u32, VarHash::HASH_SEP)
  591. }
  592. }
  593. pub struct VarHashOp {
  594. kind: HashKind,
  595. hasher: Hasher,
  596. }
  597. impl Op for VarHashOp {
  598. type Arg = HashKind;
  599. fn init(arg: Self::Arg) -> Result<Self> {
  600. let hasher = Hasher::new(arg.into())?;
  601. Ok(VarHashOp { kind: arg, hasher })
  602. }
  603. fn update(&mut self, data: &[u8]) -> Result<()> {
  604. Ok(self.hasher.update(data)?)
  605. }
  606. fn finish_into(mut self, buf: &mut [u8]) -> Result<usize> {
  607. if buf.len() < self.kind.len() {
  608. return Err(Error::IncorrectSize {
  609. expected: self.kind.len(),
  610. actual: buf.len(),
  611. });
  612. }
  613. let digest = self.hasher.finish()?;
  614. let slice = digest.as_ref();
  615. buf.copy_from_slice(slice);
  616. Ok(slice.len())
  617. }
  618. }
  619. impl HashOp for VarHashOp {
  620. type Hash = VarHash;
  621. fn kind(&self) -> HashKind {
  622. self.kind
  623. }
  624. fn finish(mut self) -> Result<Self::Hash> {
  625. let digest = self.hasher.finish()?;
  626. let mut hash: VarHash = self.kind.into();
  627. hash.as_mut().copy_from_slice(digest.as_ref());
  628. Ok(hash)
  629. }
  630. }
  631. /// A cryptographic signature.
  632. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, Default)]
  633. pub struct Signature {
  634. kind: Sign,
  635. data: Vec<u8>,
  636. }
  637. impl Signature {
  638. pub fn empty(kind: Sign) -> Signature {
  639. let data = vec![0; kind.key_len() as usize];
  640. Signature { kind, data }
  641. }
  642. #[cfg(test)]
  643. pub fn copy_from(kind: Sign, from: &[u8]) -> Signature {
  644. let mut data = vec![0; kind.key_len() as usize];
  645. data.as_mut_slice().copy_from_slice(from);
  646. Signature { kind, data }
  647. }
  648. pub fn as_slice(&self) -> &[u8] {
  649. self.data.as_slice()
  650. }
  651. pub fn as_mut_slice(&mut self) -> &mut [u8] {
  652. self.data.as_mut_slice()
  653. }
  654. }
  655. impl AsRef<[u8]> for Signature {
  656. fn as_ref(&self) -> &[u8] {
  657. self.as_slice()
  658. }
  659. }
  660. impl AsMut<[u8]> for Signature {
  661. fn as_mut(&mut self) -> &mut [u8] {
  662. self.as_mut_slice()
  663. }
  664. }
  665. #[derive(Serialize, Deserialize)]
  666. struct TaggedCiphertext<T, U> {
  667. aad: U,
  668. ciphertext: Ciphertext<T>,
  669. tag: Vec<u8>,
  670. }
  671. #[derive(EnumDiscriminants, ZeroizeOnDrop)]
  672. #[strum_discriminants(name(AeadKeyKind))]
  673. #[strum_discriminants(derive(Serialize, Deserialize))]
  674. pub enum AeadKey {
  675. AesGcm256 {
  676. key: [u8; AeadKeyKind::AesGcm256.key_len()],
  677. iv: [u8; AeadKeyKind::AesGcm256.iv_len()],
  678. },
  679. }
  680. impl AeadKeyKind {
  681. const fn key_len(self) -> usize {
  682. match self {
  683. AeadKeyKind::AesGcm256 => 32,
  684. }
  685. }
  686. const fn iv_len(self) -> usize {
  687. match self {
  688. AeadKeyKind::AesGcm256 => 16,
  689. }
  690. }
  691. }
  692. fn array_from<const N: usize>(slice: &[u8]) -> Result<[u8; N]> {
  693. let slice_len = slice.len();
  694. if N != slice_len {
  695. return Err(Error::IncorrectSize {
  696. actual: slice_len,
  697. expected: N,
  698. });
  699. }
  700. let mut array = [0u8; N];
  701. array.copy_from_slice(slice);
  702. Ok(array)
  703. }
  704. impl AeadKey {
  705. pub fn new(kind: AeadKeyKind) -> Result<AeadKey> {
  706. match kind {
  707. AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
  708. key: rand_array()?,
  709. iv: rand_array()?,
  710. }),
  711. }
  712. }
  713. fn copy_components(kind: AeadKeyKind, key_buf: &[u8], iv_buf: &[u8]) -> Result<AeadKey> {
  714. match kind {
  715. AeadKeyKind::AesGcm256 => Ok(AeadKey::AesGcm256 {
  716. key: array_from(key_buf)?,
  717. iv: array_from(iv_buf)?,
  718. }),
  719. }
  720. }
  721. fn encrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
  722. &self,
  723. aad: U,
  724. plaintext: &T,
  725. ) -> Result<TaggedCiphertext<T, U>> {
  726. let (cipher, key, iv, mut tag) = match self {
  727. AeadKey::AesGcm256 { key, iv } => (
  728. Cipher::aes_256_gcm(),
  729. key.as_slice(),
  730. iv.as_slice(),
  731. vec![0u8; 16],
  732. ),
  733. };
  734. let aad_data = to_vec(&aad)?;
  735. let plaintext_buf = to_vec(&plaintext)?;
  736. let mut ciphertext = vec![0u8; plaintext_buf.len() + cipher.block_size()];
  737. let mut crypter = Crypter::new(cipher, Mode::Encrypt, key, Some(iv))?;
  738. crypter.aad_update(&aad_data)?;
  739. let mut count = crypter.update(&plaintext_buf, &mut ciphertext)?;
  740. count += crypter.finalize(&mut ciphertext[count..])?;
  741. ciphertext.truncate(count);
  742. crypter.get_tag(&mut tag)?;
  743. Ok(TaggedCiphertext {
  744. aad,
  745. ciphertext: Ciphertext::new(ciphertext),
  746. tag,
  747. })
  748. }
  749. fn decrypt<T: Serialize + DeserializeOwned, U: Serialize + DeserializeOwned>(
  750. &self,
  751. tagged: &TaggedCiphertext<T, U>,
  752. ) -> Result<T> {
  753. let ciphertext = &tagged.ciphertext.data;
  754. let (cipher, key, iv) = match self {
  755. AeadKey::AesGcm256 { key, iv } => {
  756. (Cipher::aes_256_gcm(), key.as_slice(), iv.as_slice())
  757. }
  758. };
  759. let mut plaintext = vec![0u8; ciphertext.len() + cipher.block_size()];
  760. let mut crypter = Crypter::new(cipher, Mode::Decrypt, key, Some(iv))?;
  761. crypter.set_tag(&tagged.tag)?;
  762. let aad_buf = to_vec(&tagged.aad)?;
  763. crypter.aad_update(&aad_buf)?;
  764. let mut count = crypter.update(ciphertext, &mut plaintext)?;
  765. count += crypter.finalize(&mut plaintext[count..])?;
  766. plaintext.truncate(count);
  767. Ok(from_vec(&plaintext)?)
  768. }
  769. }
  770. #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Clone, EnumDiscriminants, ZeroizeOnDrop)]
  771. #[strum_discriminants(name(SymKeyKind))]
  772. pub enum SymKey {
  773. /// A key for the AES 256 cipher in Cipher Block Chaining mode. Note that this includes the
  774. /// initialization vector, so that a value of this variant contains all the information needed
  775. /// to fully initialize a cipher context.
  776. Aes256Cbc { key: [u8; 32], iv: [u8; 16] },
  777. /// A key for the AES 256 cipher in counter mode.
  778. Aes256Ctr { key: [u8; 32], iv: [u8; 16] },
  779. }
  780. struct SymParams<'a> {
  781. cipher: Cipher,
  782. key: &'a [u8],
  783. iv: Option<&'a [u8]>,
  784. }
  785. impl SymKey {
  786. pub(crate) fn generate(kind: SymKeyKind) -> Result<SymKey> {
  787. match kind {
  788. SymKeyKind::Aes256Cbc => Ok(SymKey::Aes256Cbc {
  789. key: rand_array()?,
  790. iv: rand_array()?,
  791. }),
  792. SymKeyKind::Aes256Ctr => Ok(SymKey::Aes256Ctr {
  793. key: rand_array()?,
  794. iv: rand_array()?,
  795. }),
  796. }
  797. }
  798. fn params(&self) -> SymParams {
  799. let (cipher, key, iv) = match self {
  800. SymKey::Aes256Cbc { key, iv } => (Cipher::aes_256_cbc(), key, Some(iv.as_slice())),
  801. SymKey::Aes256Ctr { key, iv } => (Cipher::aes_256_ctr(), key, Some(iv.as_slice())),
  802. };
  803. SymParams { cipher, key, iv }
  804. }
  805. fn block_size(&self) -> usize {
  806. let SymParams { cipher, .. } = self.params();
  807. cipher.block_size()
  808. }
  809. // The number of bytes that the plaintext expands by when encrypted.
  810. fn expansion_sz(&self) -> usize {
  811. match self {
  812. SymKey::Aes256Cbc { .. } => 16,
  813. SymKey::Aes256Ctr { .. } => 0,
  814. }
  815. }
  816. fn to_encrypter(&self) -> Result<Crypter> {
  817. let SymParams { cipher, key, iv } = self.params();
  818. Ok(Crypter::new(cipher, Mode::Encrypt, key, iv)?)
  819. }
  820. fn to_decrypter(&self) -> Result<Crypter> {
  821. let SymParams { cipher, key, iv } = self.params();
  822. Ok(Crypter::new(cipher, Mode::Decrypt, key, iv)?)
  823. }
  824. pub fn key_slice(&self) -> &[u8] {
  825. let SymParams { key, .. } = self.params();
  826. key
  827. }
  828. pub fn iv_slice(&self) -> Option<&[u8]> {
  829. let SymParams { iv, .. } = self.params();
  830. iv
  831. }
  832. }
  833. impl Encrypter for SymKey {
  834. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  835. let SymParams { cipher, key, iv } = self.params();
  836. Ok(openssl_encrypt(cipher, key, iv, slice)?)
  837. }
  838. }
  839. impl Decrypter for SymKey {
  840. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  841. let SymParams { cipher, key, iv } = self.params();
  842. Ok(openssl_decrypt(cipher, key, iv, slice)?)
  843. }
  844. }
  845. impl Default for SymKeyKind {
  846. fn default() -> Self {
  847. SymKeyKind::Aes256Ctr
  848. }
  849. }
  850. #[repr(u32)]
  851. #[derive(Debug, Display, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
  852. pub enum KeyLen {
  853. Bits256 = 32,
  854. Bits512 = 64,
  855. Bits2048 = 256,
  856. Bits3072 = 384,
  857. Bits4096 = 512,
  858. }
  859. impl KeyLen {
  860. const fn bits(self) -> u32 {
  861. 8 * self as u32
  862. }
  863. }
  864. /// A Cryptographic Scheme. This is a common type for operations such as encrypting, decrypting,
  865. /// signing and verifying.
  866. pub trait Scheme:
  867. for<'de> Deserialize<'de> + Serialize + Copy + std::fmt::Debug + PartialEq + Into<Self::Kind>
  868. {
  869. type Kind: Scheme;
  870. fn as_enum(self) -> SchemeKind;
  871. fn hash_kind(&self) -> HashKind;
  872. fn padding(&self) -> Option<OpensslPadding>;
  873. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>>;
  874. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>>;
  875. fn generate(self) -> Result<AsymKeyPair<Self::Kind>>;
  876. fn key_len(self) -> KeyLen;
  877. fn message_digest(&self) -> MessageDigest {
  878. self.hash_kind().into()
  879. }
  880. }
  881. pub enum SchemeKind {
  882. Sign(Sign),
  883. Encrypt(Encrypt),
  884. }
  885. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  886. pub enum Encrypt {
  887. RsaEsOaep(RsaEsOaep),
  888. }
  889. impl Scheme for Encrypt {
  890. type Kind = Encrypt;
  891. fn as_enum(self) -> SchemeKind {
  892. SchemeKind::Encrypt(self)
  893. }
  894. fn hash_kind(&self) -> HashKind {
  895. match self {
  896. Encrypt::RsaEsOaep(inner) => inner.hash_kind(),
  897. }
  898. }
  899. fn padding(&self) -> Option<OpensslPadding> {
  900. match self {
  901. Encrypt::RsaEsOaep(inner) => inner.padding(),
  902. }
  903. }
  904. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  905. match self {
  906. Encrypt::RsaEsOaep(inner) => inner.public_from_der(der),
  907. }
  908. }
  909. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  910. match self {
  911. Encrypt::RsaEsOaep(inner) => inner.private_from_der(der),
  912. }
  913. }
  914. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  915. match self {
  916. Encrypt::RsaEsOaep(inner) => inner.generate(),
  917. }
  918. }
  919. fn key_len(self) -> KeyLen {
  920. match self {
  921. Encrypt::RsaEsOaep(inner) => inner.key_len(),
  922. }
  923. }
  924. }
  925. impl Encrypt {
  926. pub const RSA_OAEP_2048_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
  927. key_len: KeyLen::Bits2048,
  928. hash_kind: HashKind::Sha2_256,
  929. });
  930. pub const RSA_OAEP_3072_SHA_256: Encrypt = Encrypt::RsaEsOaep(RsaEsOaep {
  931. key_len: KeyLen::Bits3072,
  932. hash_kind: HashKind::Sha2_256,
  933. });
  934. }
  935. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  936. pub enum Sign {
  937. RsaSsaPss(RsaSsaPss),
  938. }
  939. impl Default for Sign {
  940. fn default() -> Self {
  941. Self::RSA_PSS_2048_SHA_256
  942. }
  943. }
  944. impl Scheme for Sign {
  945. type Kind = Sign;
  946. fn as_enum(self) -> SchemeKind {
  947. SchemeKind::Sign(self)
  948. }
  949. fn hash_kind(&self) -> HashKind {
  950. match self {
  951. Sign::RsaSsaPss(inner) => inner.hash_kind(),
  952. }
  953. }
  954. fn padding(&self) -> Option<OpensslPadding> {
  955. match self {
  956. Sign::RsaSsaPss(inner) => inner.padding(),
  957. }
  958. }
  959. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  960. match self {
  961. Sign::RsaSsaPss(inner) => inner.public_from_der(der),
  962. }
  963. }
  964. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  965. match self {
  966. Sign::RsaSsaPss(inner) => inner.private_from_der(der),
  967. }
  968. }
  969. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  970. match self {
  971. Sign::RsaSsaPss(inner) => inner.generate(),
  972. }
  973. }
  974. fn key_len(self) -> KeyLen {
  975. self.key_len_const()
  976. }
  977. }
  978. impl Sign {
  979. pub const RSA_PSS_2048_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
  980. key_bits: KeyLen::Bits2048,
  981. hash_kind: HashKind::Sha2_256,
  982. });
  983. pub const RSA_PSS_3072_SHA_256: Sign = Sign::RsaSsaPss(RsaSsaPss {
  984. key_bits: KeyLen::Bits3072,
  985. hash_kind: HashKind::Sha2_256,
  986. });
  987. const fn key_len_const(self) -> KeyLen {
  988. match self {
  989. Sign::RsaSsaPss(inner) => inner.key_bits,
  990. }
  991. }
  992. }
  993. enum Rsa {}
  994. impl Rsa {
  995. /// The default public exponent to use for generated RSA keys.
  996. const EXP: u32 = 65537; // 2**16 + 1
  997. fn generate<S: Scheme>(scheme: S) -> Result<AsymKeyPair<S>> {
  998. let key = OsslRsa::generate(scheme.key_len().bits())?;
  999. // TODO: Separating the keys this way seems inefficient. Investigate alternatives.
  1000. let public_der = key.public_key_to_der()?;
  1001. let private_der = key.private_key_to_der()?;
  1002. let public = AsymKey::<Public, S>::new(scheme, &public_der)?;
  1003. let private = AsymKey::<Private, S>::new(scheme, &private_der)?;
  1004. Ok(AsymKeyPair { public, private })
  1005. }
  1006. }
  1007. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1008. pub struct RsaEsOaep {
  1009. key_len: KeyLen,
  1010. hash_kind: HashKind,
  1011. }
  1012. impl Scheme for RsaEsOaep {
  1013. type Kind = Encrypt;
  1014. fn as_enum(self) -> SchemeKind {
  1015. SchemeKind::Encrypt(self.into())
  1016. }
  1017. fn hash_kind(&self) -> HashKind {
  1018. self.hash_kind
  1019. }
  1020. fn padding(&self) -> Option<OpensslPadding> {
  1021. Some(OpensslPadding::PKCS1_OAEP)
  1022. }
  1023. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1024. Ok(PKey::public_key_from_der(der)?.conv_pub())
  1025. }
  1026. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1027. Ok(PKey::private_key_from_der(der)?.conv_priv())
  1028. }
  1029. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1030. Rsa::generate(self.into())
  1031. }
  1032. fn key_len(self) -> KeyLen {
  1033. self.key_len
  1034. }
  1035. }
  1036. impl From<RsaEsOaep> for Encrypt {
  1037. fn from(scheme: RsaEsOaep) -> Self {
  1038. Encrypt::RsaEsOaep(scheme)
  1039. }
  1040. }
  1041. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, Copy)]
  1042. pub struct RsaSsaPss {
  1043. key_bits: KeyLen,
  1044. hash_kind: HashKind,
  1045. }
  1046. impl Scheme for RsaSsaPss {
  1047. type Kind = Sign;
  1048. fn as_enum(self) -> SchemeKind {
  1049. SchemeKind::Sign(self.into())
  1050. }
  1051. fn hash_kind(&self) -> HashKind {
  1052. self.hash_kind
  1053. }
  1054. fn padding(&self) -> Option<OpensslPadding> {
  1055. Some(OpensslPadding::PKCS1_PSS)
  1056. }
  1057. fn public_from_der(self, der: &[u8]) -> Result<PKey<Public>> {
  1058. Ok(PKey::public_key_from_der(der)?.conv_pub())
  1059. }
  1060. fn private_from_der(self, der: &[u8]) -> Result<PKey<Private>> {
  1061. Ok(PKey::private_key_from_der(der)?.conv_priv())
  1062. }
  1063. fn generate(self) -> Result<AsymKeyPair<Self::Kind>> {
  1064. Rsa::generate(self.into())
  1065. }
  1066. fn key_len(self) -> KeyLen {
  1067. self.key_bits
  1068. }
  1069. }
  1070. impl From<RsaSsaPss> for Sign {
  1071. fn from(scheme: RsaSsaPss) -> Self {
  1072. Sign::RsaSsaPss(scheme)
  1073. }
  1074. }
  1075. /// Marker trait for the `Public` and `Private` key privacy types.
  1076. pub trait KeyPrivacy {}
  1077. /// Represents keys which can be shared freely.
  1078. #[derive(Clone, Debug)]
  1079. pub enum Public {}
  1080. impl KeyPrivacy for Public {}
  1081. unsafe impl HasPublic for Public {}
  1082. #[derive(Debug, Clone)]
  1083. /// Represents keys which must be kept confidential.
  1084. pub enum Private {}
  1085. impl KeyPrivacy for Private {}
  1086. unsafe impl HasPrivate for Private {}
  1087. trait PKeyExt<T> {
  1088. /// Converts a PKey<T> to a PKey<U>. This hack allows for converting between openssl's
  1089. /// Public and Private types and ours.
  1090. fn conv_pkey<U>(self) -> PKey<U>;
  1091. /// Convert from openssl's Public type to `crypto::Public`.
  1092. fn conv_pub(self) -> PKey<Public>;
  1093. /// Convert from openssl's Private type to `crypto::Private`.
  1094. fn conv_priv(self) -> PKey<Private>;
  1095. }
  1096. impl<T> PKeyExt<T> for PKey<T> {
  1097. fn conv_pkey<U>(self) -> PKey<U> {
  1098. let ptr = self.as_ptr();
  1099. let new_pkey = unsafe { PKey::from_ptr(ptr) };
  1100. std::mem::forget(self);
  1101. new_pkey
  1102. }
  1103. fn conv_pub(self) -> PKey<Public> {
  1104. self.conv_pkey()
  1105. }
  1106. fn conv_priv(self) -> PKey<Private> {
  1107. self.conv_pkey()
  1108. }
  1109. }
  1110. /// Represents any kind of asymmetric key.
  1111. #[derive(Debug, Clone)]
  1112. pub struct AsymKey<P, S> {
  1113. scheme: S,
  1114. pkey: PKey<P>,
  1115. }
  1116. impl<P, S: Copy> AsymKey<P, S> {
  1117. pub fn scheme(&self) -> S {
  1118. self.scheme
  1119. }
  1120. }
  1121. pub type AsymKeyPub<S> = AsymKey<Public, S>;
  1122. impl<S: Scheme> AsymKey<Public, S> {
  1123. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Public, S>> {
  1124. let pkey = scheme.public_from_der(der)?;
  1125. Ok(AsymKey { scheme, pkey })
  1126. }
  1127. }
  1128. impl<S: Scheme> AsymKey<Private, S> {
  1129. pub(crate) fn new(scheme: S, der: &[u8]) -> Result<AsymKey<Private, S>> {
  1130. let pkey = scheme.private_from_der(der)?;
  1131. Ok(AsymKey { scheme, pkey })
  1132. }
  1133. }
  1134. impl<'de, S: Scheme> Deserialize<'de> for AsymKey<Public, S> {
  1135. fn deserialize<D: Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
  1136. const FIELDS: &[&str] = &["scheme", "pkey"];
  1137. struct StructVisitor<S: Scheme>(PhantomData<S>);
  1138. impl<'de, S: Scheme> Visitor<'de> for StructVisitor<S> {
  1139. type Value = AsymKey<Public, S>;
  1140. fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  1141. formatter.write_fmt(format_args!("struct {}", stringify!(AsymKey)))
  1142. }
  1143. fn visit_seq<V: SeqAccess<'de>>(
  1144. self,
  1145. mut seq: V,
  1146. ) -> std::result::Result<Self::Value, V::Error> {
  1147. let scheme: S = seq
  1148. .next_element()?
  1149. .ok_or_else(|| de::Error::missing_field(FIELDS[0]))?;
  1150. let der: Vec<u8> = seq
  1151. .next_element()?
  1152. .ok_or_else(|| de::Error::missing_field(FIELDS[1]))?;
  1153. AsymKey::<Public, _>::new(scheme, der.as_slice()).map_err(de::Error::custom)
  1154. }
  1155. }
  1156. d.deserialize_struct(stringify!(AsymKey), FIELDS, StructVisitor(PhantomData))
  1157. }
  1158. }
  1159. impl<S: Scheme> Serialize for AsymKey<Public, S> {
  1160. fn serialize<T: Serializer>(&self, s: T) -> std::result::Result<T::Ok, T::Error> {
  1161. let mut struct_s = s.serialize_struct(stringify!(AsymKey), 2)?;
  1162. struct_s.serialize_field("scheme", &self.scheme)?;
  1163. let der = self.pkey.public_key_to_der().unwrap();
  1164. struct_s.serialize_field("pkey", der.as_slice())?;
  1165. struct_s.end()
  1166. }
  1167. }
  1168. impl<S: Scheme> PartialEq for AsymKey<Public, S> {
  1169. fn eq(&self, other: &Self) -> bool {
  1170. self.scheme == other.scheme && self.pkey.public_eq(&other.pkey)
  1171. }
  1172. }
  1173. impl Principaled for AsymKey<Public, Sign> {
  1174. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1175. let der = self.pkey.public_key_to_der().unwrap();
  1176. let bytes = hash(kind.into(), der.as_slice()).unwrap();
  1177. let mut hash_buf = VarHash::from(kind);
  1178. hash_buf.as_mut().copy_from_slice(&bytes);
  1179. Principal(hash_buf)
  1180. }
  1181. }
  1182. impl Encrypter for AsymKey<Public, Encrypt> {
  1183. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1184. let mut encrypter = OsslEncrypter::new(&self.pkey)?;
  1185. if let Some(padding) = self.scheme.padding() {
  1186. encrypter.set_rsa_padding(padding)?;
  1187. }
  1188. {
  1189. let Encrypt::RsaEsOaep(inner) = self.scheme;
  1190. encrypter.set_rsa_oaep_md(inner.message_digest())?;
  1191. }
  1192. let buffer_len = encrypter.encrypt_len(slice)?;
  1193. let mut ciphertext = vec![0; buffer_len];
  1194. let ciphertext_len = encrypter.encrypt(slice, &mut ciphertext)?;
  1195. ciphertext.truncate(ciphertext_len);
  1196. Ok(ciphertext)
  1197. }
  1198. }
  1199. impl Decrypter for AsymKey<Private, Encrypt> {
  1200. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1201. let mut decrypter = OsslDecrypter::new(&self.pkey)?;
  1202. if let Some(padding) = self.scheme.padding() {
  1203. decrypter.set_rsa_padding(padding)?;
  1204. }
  1205. {
  1206. let Encrypt::RsaEsOaep(inner) = self.scheme;
  1207. decrypter.set_rsa_oaep_md(inner.message_digest())?;
  1208. }
  1209. let buffer_len = decrypter.decrypt_len(slice)?;
  1210. let mut plaintext = vec![0; buffer_len];
  1211. let plaintext_len = decrypter.decrypt(slice, &mut plaintext)?;
  1212. plaintext.truncate(plaintext_len);
  1213. Ok(plaintext)
  1214. }
  1215. }
  1216. impl Signer for AsymKey<Private, Sign> {
  1217. type Op<'s> = OsslSignOp<'s>;
  1218. fn init_sign(&self) -> Result<Self::Op<'_>> {
  1219. OsslSignOp::init((self.scheme, self.pkey.as_ref()))
  1220. }
  1221. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1222. let mut signer = OsslSigner::new(self.scheme.message_digest(), &self.pkey)?;
  1223. if let Some(padding) = self.scheme.padding() {
  1224. signer.set_rsa_padding(padding)?;
  1225. }
  1226. for part in parts {
  1227. signer.update(part)?;
  1228. }
  1229. let mut signature = Signature::empty(self.scheme);
  1230. signer.sign(signature.as_mut_slice())?;
  1231. Ok(signature)
  1232. }
  1233. }
  1234. impl Verifier for AsymKey<Public, Sign> {
  1235. type Op<'v> = OsslVerifyOp<'v>;
  1236. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1237. OsslVerifyOp::init((self.scheme, self.pkey.as_ref()))
  1238. }
  1239. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1240. let mut verifier = OsslVerifier::new(self.scheme.message_digest(), &self.pkey)?;
  1241. if let Some(padding) = self.scheme.padding() {
  1242. verifier.set_rsa_padding(padding)?;
  1243. }
  1244. for part in parts {
  1245. verifier.update(part)?;
  1246. }
  1247. if verifier.verify(signature)? {
  1248. Ok(())
  1249. } else {
  1250. Err(Error::InvalidSignature)
  1251. }
  1252. }
  1253. }
  1254. #[derive(Clone)]
  1255. pub struct AsymKeyPair<S: Scheme> {
  1256. public: AsymKey<Public, S>,
  1257. private: AsymKey<Private, S>,
  1258. }
  1259. impl<S: Scheme> AsymKeyPair<S> {
  1260. pub fn new(scheme: S, public_der: &[u8], private_der: &[u8]) -> Result<AsymKeyPair<S>> {
  1261. let public = AsymKey::<Public, _>::new(scheme, public_der)?;
  1262. let private = AsymKey::<Private, _>::new(scheme, private_der)?;
  1263. Ok(AsymKeyPair { public, private })
  1264. }
  1265. }
  1266. // Note that only signing keys are associated with a Principal.
  1267. impl Principaled for AsymKeyPair<Sign> {
  1268. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1269. self.public.principal_of_kind(kind)
  1270. }
  1271. }
  1272. impl Encrypter for AsymKeyPair<Encrypt> {
  1273. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1274. self.public.encrypt(slice)
  1275. }
  1276. }
  1277. impl Decrypter for AsymKeyPair<Encrypt> {
  1278. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1279. self.private.decrypt(slice)
  1280. }
  1281. }
  1282. impl Signer for AsymKeyPair<Sign> {
  1283. type Op<'s> = <AsymKey<Private, Sign> as Signer>::Op<'s>;
  1284. fn init_sign(&self) -> Result<Self::Op<'_>> {
  1285. self.private.init_sign()
  1286. }
  1287. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1288. self.private.sign(parts)
  1289. }
  1290. }
  1291. impl Verifier for AsymKeyPair<Sign> {
  1292. type Op<'v> = OsslVerifyOp<'v>;
  1293. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1294. self.public.init_verify()
  1295. }
  1296. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1297. self.public.verify(parts, signature)
  1298. }
  1299. }
  1300. #[derive(Debug, Clone, Serialize, Deserialize)]
  1301. pub struct PublicCreds {
  1302. sign: AsymKeyPub<Sign>,
  1303. enc: AsymKeyPub<Encrypt>,
  1304. }
  1305. impl Principaled for PublicCreds {
  1306. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1307. self.sign.principal_of_kind(kind)
  1308. }
  1309. }
  1310. impl Encrypter for PublicCreds {
  1311. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1312. self.enc.encrypt(slice)
  1313. }
  1314. }
  1315. impl Verifier for PublicCreds {
  1316. type Op<'v> = OsslVerifyOp<'v>;
  1317. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1318. self.sign.init_verify()
  1319. }
  1320. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1321. self.sign.verify(parts, signature)
  1322. }
  1323. }
  1324. impl CredsPub for PublicCreds {
  1325. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1326. &self.sign
  1327. }
  1328. }
  1329. impl PartialEq for PublicCreds {
  1330. fn eq(&self, other: &Self) -> bool {
  1331. self.principal() == other.principal()
  1332. }
  1333. }
  1334. #[derive(Clone)]
  1335. pub struct ConcreteCreds {
  1336. sign: AsymKeyPair<Sign>,
  1337. encrypt: AsymKeyPair<Encrypt>,
  1338. writecap: Option<Writecap>,
  1339. }
  1340. impl ConcreteCreds {
  1341. pub fn new(sign: AsymKeyPair<Sign>, encrypt: AsymKeyPair<Encrypt>) -> ConcreteCreds {
  1342. ConcreteCreds {
  1343. sign,
  1344. encrypt,
  1345. writecap: None,
  1346. }
  1347. }
  1348. #[cfg(test)]
  1349. pub fn generate() -> Result<ConcreteCreds> {
  1350. let encrypt = Encrypt::RSA_OAEP_3072_SHA_256.generate()?;
  1351. let sign = Sign::RSA_PSS_3072_SHA_256.generate()?;
  1352. Ok(ConcreteCreds {
  1353. sign,
  1354. encrypt,
  1355. writecap: None,
  1356. })
  1357. }
  1358. pub fn set_writecap(&mut self, writecap: Writecap) {
  1359. self.writecap = Some(writecap)
  1360. }
  1361. }
  1362. impl Verifier for ConcreteCreds {
  1363. type Op<'v> = OsslVerifyOp<'v>;
  1364. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1365. self.sign.init_verify()
  1366. }
  1367. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1368. self.sign.verify(parts, signature)
  1369. }
  1370. }
  1371. impl Encrypter for ConcreteCreds {
  1372. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1373. self.encrypt.encrypt(slice)
  1374. }
  1375. }
  1376. impl Principaled for ConcreteCreds {
  1377. fn principal_of_kind(&self, kind: HashKind) -> Principal {
  1378. self.sign.principal_of_kind(kind)
  1379. }
  1380. }
  1381. impl CredsPub for ConcreteCreds {
  1382. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1383. &self.sign.public
  1384. }
  1385. }
  1386. impl Signer for ConcreteCreds {
  1387. type Op<'s> = <AsymKeyPair<Sign> as Signer>::Op<'s>;
  1388. fn init_sign(&self) -> Result<Self::Op<'_>> {
  1389. self.sign.init_sign()
  1390. }
  1391. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1392. self.sign.sign(parts)
  1393. }
  1394. }
  1395. impl Decrypter for ConcreteCreds {
  1396. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1397. self.encrypt.decrypt(slice)
  1398. }
  1399. }
  1400. impl CredsPriv for ConcreteCreds {
  1401. fn writecap(&self) -> Option<&Writecap> {
  1402. self.writecap.as_ref()
  1403. }
  1404. }
  1405. impl Creds for ConcreteCreds {}
  1406. pub trait Encrypter {
  1407. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  1408. }
  1409. impl<T: Encrypter> Encrypter for &T {
  1410. fn encrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1411. (*self).encrypt(slice)
  1412. }
  1413. }
  1414. pub trait EncrypterExt: Encrypter {
  1415. /// Serializes the given value into a new vector, then encrypts it and returns the resulting
  1416. /// ciphertext.
  1417. fn ser_encrypt<T: Serialize>(&self, value: &T) -> Result<Ciphertext<T>> {
  1418. let data = to_vec(value)?;
  1419. let data = self.encrypt(&data)?;
  1420. Ok(Ciphertext::new(data))
  1421. }
  1422. }
  1423. impl<T: Encrypter + ?Sized> EncrypterExt for T {}
  1424. pub trait Decrypter {
  1425. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>>;
  1426. }
  1427. impl<T: Decrypter> Decrypter for &T {
  1428. fn decrypt(&self, slice: &[u8]) -> Result<Vec<u8>> {
  1429. (*self).decrypt(slice)
  1430. }
  1431. }
  1432. pub trait DecrypterExt: Decrypter {
  1433. fn ser_decrypt<T: DeserializeOwned>(&self, ct: &Ciphertext<T>) -> Result<T> {
  1434. let pt = self.decrypt(ct.data.as_slice())?;
  1435. Ok(from_vec(&pt)?)
  1436. }
  1437. }
  1438. impl<T: Decrypter + ?Sized> DecrypterExt for T {}
  1439. /// Represents an ongoing signing operation.
  1440. pub trait SignOp: Op {
  1441. /// Returns the signature scheme that this operation is using.
  1442. fn scheme(&self) -> Sign;
  1443. /// Finishes this signature operation and returns a new signature containing the result.
  1444. fn finish(self) -> Result<Signature> {
  1445. let scheme = self.scheme();
  1446. let mut sig = Signature::empty(scheme);
  1447. self.finish_into(sig.as_mut())?;
  1448. Ok(sig)
  1449. }
  1450. }
  1451. pub struct OsslSignOp<'a> {
  1452. signer: OsslSigner<'a>,
  1453. scheme: Sign,
  1454. }
  1455. impl<'a> Op for OsslSignOp<'a> {
  1456. type Arg = (Sign, &'a PKeyRef<Private>);
  1457. fn init(arg: Self::Arg) -> Result<Self> {
  1458. let scheme = arg.0;
  1459. let mut signer = OsslSigner::new(arg.0.message_digest(), arg.1)?;
  1460. if let Some(padding) = scheme.padding() {
  1461. signer.set_rsa_padding(padding)?;
  1462. }
  1463. Ok(OsslSignOp { signer, scheme })
  1464. }
  1465. fn update(&mut self, data: &[u8]) -> Result<()> {
  1466. Ok(self.signer.update(data)?)
  1467. }
  1468. fn finish_into(self, buf: &mut [u8]) -> Result<usize> {
  1469. Ok(self.signer.sign(buf)?)
  1470. }
  1471. }
  1472. impl<'a> SignOp for OsslSignOp<'a> {
  1473. fn scheme(&self) -> Sign {
  1474. self.scheme
  1475. }
  1476. }
  1477. /// A struct which computes a signature over data as it is written to it.
  1478. pub struct SignWrite<T, Op> {
  1479. inner: T,
  1480. op: Op,
  1481. }
  1482. impl<T, Op: SignOp> SignWrite<T, Op> {
  1483. pub fn new(inner: T, op: Op) -> Self {
  1484. SignWrite { inner, op }
  1485. }
  1486. pub fn finish_into(self, buf: &mut [u8]) -> Result<(usize, T)> {
  1487. Ok((self.op.finish_into(buf)?, self.inner))
  1488. }
  1489. pub fn finish(self) -> Result<(Signature, T)> {
  1490. Ok((self.op.finish()?, self.inner))
  1491. }
  1492. }
  1493. impl<T: Write, Op: SignOp> Write for SignWrite<T, Op> {
  1494. fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
  1495. self.op.update(buf)?;
  1496. self.inner.write(buf)
  1497. }
  1498. fn flush(&mut self) -> io::Result<()> {
  1499. self.inner.flush()
  1500. }
  1501. }
  1502. pub trait Signer {
  1503. type Op<'s>: SignOp
  1504. where
  1505. Self: 's;
  1506. /// Starts a new signing operation and returns the struct representing it.
  1507. fn init_sign(&self) -> Result<Self::Op<'_>>;
  1508. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature>;
  1509. fn ser_sign<T: Serialize>(&self, value: &T) -> Result<Signed<T>> {
  1510. let data = to_vec(value)?;
  1511. let sig = self.sign(std::iter::once(data.as_slice()))?;
  1512. Ok(Signed::new(data, sig))
  1513. }
  1514. fn sign_writecap(&self, writecap: &mut Writecap) -> Result<()> {
  1515. let signed = self.ser_sign(&writecap.body)?;
  1516. writecap.signature = signed.sig;
  1517. Ok(())
  1518. }
  1519. fn ser_sign_into<T: Serialize>(&self, value: &T, buf: &mut Vec<u8>) -> Result<Signature> {
  1520. write_to(value, buf)?;
  1521. self.sign(std::iter::once(buf.as_slice()))
  1522. }
  1523. }
  1524. impl<T: Signer> Signer for &T {
  1525. type Op<'s> = T::Op<'s> where Self: 's;
  1526. fn init_sign(&self) -> Result<Self::Op<'_>> {
  1527. (*self).init_sign()
  1528. }
  1529. fn sign<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I) -> Result<Signature> {
  1530. (*self).sign(parts)
  1531. }
  1532. }
  1533. pub trait VerifyOp: Sized {
  1534. type Arg;
  1535. fn init(arg: Self::Arg) -> Result<Self>;
  1536. fn update(&mut self, data: &[u8]) -> Result<()>;
  1537. fn finish(self, sig: &[u8]) -> Result<()>;
  1538. fn scheme(&self) -> Sign;
  1539. }
  1540. pub struct OsslVerifyOp<'a> {
  1541. verifier: OsslVerifier<'a>,
  1542. scheme: Sign,
  1543. }
  1544. impl<'a> VerifyOp for OsslVerifyOp<'a> {
  1545. type Arg = (Sign, &'a PKeyRef<Public>);
  1546. fn init(arg: Self::Arg) -> Result<Self> {
  1547. let scheme = arg.0;
  1548. let mut verifier = OsslVerifier::new(scheme.message_digest(), arg.1)?;
  1549. if let Some(padding) = scheme.padding() {
  1550. verifier.set_rsa_padding(padding)?;
  1551. }
  1552. Ok(OsslVerifyOp { verifier, scheme })
  1553. }
  1554. fn update(&mut self, data: &[u8]) -> Result<()> {
  1555. Ok(self.verifier.update(data)?)
  1556. }
  1557. fn finish(self, sig: &[u8]) -> Result<()> {
  1558. match self.verifier.verify(sig) {
  1559. Ok(true) => Ok(()),
  1560. Ok(false) => Err(Error::InvalidSignature),
  1561. Err(err) => Err(err.into()),
  1562. }
  1563. }
  1564. fn scheme(&self) -> Sign {
  1565. self.scheme
  1566. }
  1567. }
  1568. pub struct VerifyRead<T, Op> {
  1569. inner: T,
  1570. op: Op,
  1571. update_failed: bool,
  1572. }
  1573. impl<T: Read, Op: VerifyOp> VerifyRead<T, Op> {
  1574. pub fn new(inner: T, op: Op) -> Self {
  1575. VerifyRead {
  1576. inner,
  1577. op,
  1578. update_failed: false,
  1579. }
  1580. }
  1581. pub fn finish(self, sig: &[u8]) -> std::result::Result<T, (T, Error)> {
  1582. if self.update_failed {
  1583. return Err((
  1584. self.inner,
  1585. Error::custom("VerifyRead::finish: update_failed was true"),
  1586. ));
  1587. }
  1588. match self.op.finish(sig) {
  1589. Ok(_) => Ok(self.inner),
  1590. Err(err) => Err((self.inner, err)),
  1591. }
  1592. }
  1593. }
  1594. impl<T: Read, Op: VerifyOp> Read for VerifyRead<T, Op> {
  1595. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
  1596. if self.update_failed {
  1597. return Err(Error::custom("VerifyRead::read update previously failed").into());
  1598. }
  1599. let read = self.inner.read(buf)?;
  1600. if read > 0 {
  1601. if let Err(err) = self.op.update(&buf[..read]) {
  1602. self.update_failed = true;
  1603. error!("VerifyRead::read failed to update VerifyOp: {err}");
  1604. }
  1605. }
  1606. Ok(read)
  1607. }
  1608. }
  1609. pub trait Verifier {
  1610. type Op<'v>: VerifyOp
  1611. where
  1612. Self: 'v;
  1613. fn init_verify(&self) -> Result<Self::Op<'_>>;
  1614. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()>;
  1615. fn ser_verify<T: Serialize>(&self, value: &T, signature: &[u8]) -> Result<()> {
  1616. let data = to_vec(value)?;
  1617. self.verify(std::iter::once(data.as_slice()), signature)
  1618. }
  1619. }
  1620. impl<T: Verifier> Verifier for &T {
  1621. type Op<'v> = T::Op<'v> where Self: 'v;
  1622. fn init_verify(&self) -> Result<Self::Op<'_>> {
  1623. (*self).init_verify()
  1624. }
  1625. fn verify<'a, I: Iterator<Item = &'a [u8]>>(&self, parts: I, signature: &[u8]) -> Result<()> {
  1626. (*self).verify(parts, signature)
  1627. }
  1628. }
  1629. /// Trait for types which can be used as public credentials.
  1630. pub trait CredsPub: Verifier + Encrypter + Principaled {
  1631. /// Returns a reference to the public signing key which can be used to verify signatures.
  1632. fn public_sign(&self) -> &AsymKey<Public, Sign>;
  1633. }
  1634. impl<T: CredsPub> CredsPub for &T {
  1635. fn public_sign(&self) -> &AsymKey<Public, Sign> {
  1636. (*self).public_sign()
  1637. }
  1638. }
  1639. /// Trait for types which contain private credentials.
  1640. pub trait CredsPriv: Decrypter + Signer {
  1641. /// Returns a reference to the writecap associated with these credentials, if one has been
  1642. /// issued.
  1643. fn writecap(&self) -> Option<&Writecap>;
  1644. }
  1645. impl<T: CredsPriv> CredsPriv for &T {
  1646. fn writecap(&self) -> Option<&Writecap> {
  1647. (*self).writecap()
  1648. }
  1649. }
  1650. /// Trait for types which contain both public and private credentials.
  1651. pub trait Creds: CredsPriv + CredsPub + Clone {
  1652. fn issue_writecap(
  1653. &self,
  1654. issued_to: Principal,
  1655. path_components: Vec<String>,
  1656. expires: Epoch,
  1657. ) -> Result<Writecap> {
  1658. let path = BlockPath::new(self.principal(), path_components);
  1659. let body = WritecapBody {
  1660. issued_to,
  1661. path,
  1662. expires,
  1663. signing_key: self.public_sign().to_owned(),
  1664. };
  1665. let signed = self.ser_sign(&body)?;
  1666. Ok(Writecap {
  1667. body,
  1668. signature: signed.sig,
  1669. next: self.writecap().map(|e| Box::new(e.to_owned())),
  1670. })
  1671. }
  1672. }
  1673. impl<C: Creds> Creds for &C {
  1674. fn issue_writecap(
  1675. &self,
  1676. issued_to: Principal,
  1677. path_components: Vec<String>,
  1678. expires: Epoch,
  1679. ) -> Result<Writecap> {
  1680. (*self).issue_writecap(issued_to, path_components, expires)
  1681. }
  1682. }
  1683. /// A trait for types which store credentials.
  1684. pub trait CredStore {
  1685. type CredHandle: Creds;
  1686. type ExportedCreds: Serialize + for<'de> Deserialize<'de>;
  1687. /// Returns the node credentials. If credentials haven't been generated, they are generated
  1688. /// stored and returned.
  1689. fn node_creds(&self) -> Result<Self::CredHandle>;
  1690. /// Returns the root credentials. If no root credentials have been generated, or the provided
  1691. /// password is incorrect, then an error is returned.
  1692. fn root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  1693. /// Generates the root credentials and protects them using the given password. If the root
  1694. /// credentials have already been generated then an error is returned.
  1695. fn gen_root_creds(&self, password: &str) -> Result<Self::CredHandle>;
  1696. fn storage_key(&self) -> Result<AsymKeyPub<Encrypt>>;
  1697. fn export_root_creds(
  1698. &self,
  1699. root_creds: &Self::CredHandle,
  1700. password: &str,
  1701. new_parent: &AsymKeyPub<Encrypt>,
  1702. ) -> Result<Self::ExportedCreds>;
  1703. fn import_root_creds(
  1704. &self,
  1705. password: &str,
  1706. exported: Self::ExportedCreds,
  1707. ) -> Result<Self::CredHandle>;
  1708. fn assign_node_writecap(&self, handle: &mut Self::CredHandle, writecap: Writecap)
  1709. -> Result<()>;
  1710. }
  1711. impl BlockMeta {
  1712. /// Validates that this metadata struct contains a valid writecap, that this writecap is
  1713. /// permitted to write to the path of this block and that the signature in this metadata struct
  1714. /// is valid and matches the key the writecap was issued to.
  1715. pub fn assert_valid(&self, path: &BlockPath) -> Result<()> {
  1716. let body = &self.body;
  1717. let writecap = body
  1718. .writecap
  1719. .as_ref()
  1720. .ok_or(crate::Error::MissingWritecap)?;
  1721. writecap.assert_valid_for(path)?;
  1722. let signed_by = body.signing_key.principal();
  1723. if writecap.body.issued_to != signed_by {
  1724. return Err(Error::signature_mismatch(
  1725. writecap.body.issued_to.clone(),
  1726. signed_by,
  1727. ));
  1728. }
  1729. body.signing_key.ser_verify(&body, self.sig.as_slice())
  1730. }
  1731. }
  1732. /// The types of errors which can occur when verifying a writecap chain is authorized to write to
  1733. /// a given path.
  1734. #[derive(Debug, PartialEq, Eq, Display)]
  1735. pub enum WritecapAuthzErr {
  1736. /// The chain is not valid for use on the given path.
  1737. UnauthorizedPath,
  1738. /// At least one writecap in the chain is expired.
  1739. Expired,
  1740. /// The given writecaps do not actually form a chain.
  1741. NotChained,
  1742. /// The principal the root writecap was issued to does not own the given path.
  1743. RootDoesNotOwnPath,
  1744. /// An error occurred while serializing a writecap.
  1745. Serde(String),
  1746. /// The write cap chain was too long to be validated. The value contained in this error is
  1747. /// the maximum allowed length.
  1748. ChainTooLong(usize),
  1749. }
  1750. impl Writecap {
  1751. /// Verifies that the given `Writecap` actually grants permission to write to the given `Path`.
  1752. pub fn assert_valid_for(&self, path: &BlockPath) -> Result<()> {
  1753. let mut writecap = self;
  1754. const CHAIN_LEN_LIMIT: usize = 256;
  1755. let mut prev: Option<&Writecap> = None;
  1756. let mut sig_input_buf = Vec::new();
  1757. let now = Epoch::now();
  1758. for _ in 0..CHAIN_LEN_LIMIT {
  1759. if !writecap.body.path.contains(path) {
  1760. return Err(WritecapAuthzErr::UnauthorizedPath.into());
  1761. }
  1762. if writecap.body.expires <= now {
  1763. return Err(WritecapAuthzErr::Expired.into());
  1764. }
  1765. if let Some(prev) = &prev {
  1766. if prev
  1767. .body
  1768. .signing_key
  1769. .principal_of_kind(writecap.body.issued_to.kind())
  1770. != writecap.body.issued_to
  1771. {
  1772. return Err(WritecapAuthzErr::NotChained.into());
  1773. }
  1774. }
  1775. sig_input_buf.clear();
  1776. write_to(&writecap.body, &mut sig_input_buf)
  1777. .map_err(|e| WritecapAuthzErr::Serde(e.to_string()))?;
  1778. writecap.body.signing_key.verify(
  1779. std::iter::once(sig_input_buf.as_slice()),
  1780. writecap.signature.as_slice(),
  1781. )?;
  1782. match &writecap.next {
  1783. Some(next) => {
  1784. prev = Some(writecap);
  1785. writecap = next;
  1786. }
  1787. None => {
  1788. // We're at the root key. As long as the signer of this writecap is the owner of
  1789. // the path, then the writecap is valid.
  1790. if writecap
  1791. .body
  1792. .signing_key
  1793. .principal_of_kind(path.root().kind())
  1794. == *path.root()
  1795. {
  1796. return Ok(());
  1797. } else {
  1798. return Err(WritecapAuthzErr::RootDoesNotOwnPath.into());
  1799. }
  1800. }
  1801. }
  1802. }
  1803. Err(WritecapAuthzErr::ChainTooLong(CHAIN_LEN_LIMIT).into())
  1804. }
  1805. }
  1806. #[cfg(test)]
  1807. mod tests {
  1808. use super::*;
  1809. use crate::{
  1810. crypto::secret_stream::SecretStream,
  1811. test_helpers::{self, *},
  1812. BrotliParams, Sectored, SectoredBuf, TryCompose,
  1813. };
  1814. use std::{
  1815. io::{Seek, SeekFrom},
  1816. time::Duration,
  1817. };
  1818. #[test]
  1819. fn encrypt_decrypt_block() {
  1820. const SECT_SZ: usize = 16;
  1821. const SECT_CT: usize = 8;
  1822. let creds = make_key_pair();
  1823. let mut block = make_block_with(&creds);
  1824. write_fill(&mut block, SECT_SZ, SECT_CT);
  1825. block.seek(SeekFrom::Start(0)).expect("seek failed");
  1826. read_check(block, SECT_SZ, SECT_CT);
  1827. }
  1828. #[test]
  1829. fn rsa_sign_and_verify() -> Result<()> {
  1830. let key = make_key_pair();
  1831. let header = b"About: lyrics".as_slice();
  1832. let message = b"Everything that feels so good is bad bad bad.".as_slice();
  1833. let signature = key.sign([header, message].into_iter())?;
  1834. key.verify([header, message].into_iter(), signature.as_slice())
  1835. }
  1836. #[test]
  1837. fn hash_to_string() {
  1838. let hash = make_principal().0;
  1839. let string = hash.to_string();
  1840. assert_eq!("0!dSip4J0kurN5VhVo_aTipM-ywOOWrqJuRRVQ7aa-bew", string)
  1841. }
  1842. #[test]
  1843. fn hash_to_string_round_trip() -> Result<()> {
  1844. let expected = make_principal().0;
  1845. let string = expected.to_string();
  1846. let actual = VarHash::try_from(string.as_str())?;
  1847. assert_eq!(expected, actual);
  1848. Ok(())
  1849. }
  1850. #[test]
  1851. fn verify_writecap_valid() {
  1852. let writecap = make_writecap(vec!["apps", "verse"]);
  1853. writecap
  1854. .assert_valid_for(&writecap.body.path)
  1855. .expect("failed to verify writecap");
  1856. }
  1857. #[test]
  1858. fn verify_writecap_invalid_signature() -> Result<()> {
  1859. let mut writecap = make_writecap(vec!["apps", "verse"]);
  1860. writecap.signature = Signature::empty(Sign::RSA_PSS_3072_SHA_256);
  1861. let result = writecap.assert_valid_for(&writecap.body.path);
  1862. if let Err(Error::InvalidSignature) = result {
  1863. Ok(())
  1864. } else {
  1865. Err(Error::custom(format!("unexpected result {:?}", result)))
  1866. }
  1867. }
  1868. fn assert_authz_err<T: std::fmt::Debug>(
  1869. expected: WritecapAuthzErr,
  1870. result: Result<T>,
  1871. ) -> Result<()> {
  1872. if let Err(Error::WritecapAuthzErr(actual)) = &result {
  1873. if *actual == expected {
  1874. return Ok(());
  1875. }
  1876. }
  1877. Err(Error::custom(format!("unexpected result: {:?}", result)))
  1878. }
  1879. #[test]
  1880. fn verify_writecap_invalid_path_not_contained() -> Result<()> {
  1881. let writecap = make_writecap(vec!["apps", "verse"]);
  1882. let mut path = writecap.body.path.clone();
  1883. path.pop_component();
  1884. // `path` is now a superpath of `writecap.path`, thus the writecap is not authorized to
  1885. // write to it.
  1886. let result = writecap.assert_valid_for(&path);
  1887. assert_authz_err(WritecapAuthzErr::UnauthorizedPath, result)
  1888. }
  1889. #[test]
  1890. fn verify_writecap_invalid_expired() -> Result<()> {
  1891. let mut writecap = make_writecap(vec!["apps", "verse"]);
  1892. writecap.body.expires = Epoch::now() - Duration::from_secs(1);
  1893. let result = writecap.assert_valid_for(&writecap.body.path);
  1894. assert_authz_err(WritecapAuthzErr::Expired, result)
  1895. }
  1896. #[test]
  1897. fn verify_writecap_invalid_not_chained() -> Result<()> {
  1898. let (mut root_writecap, root_key) = make_self_signed_writecap();
  1899. root_writecap.body.issued_to = Principal(VarHash::from(HashKind::Sha2_256));
  1900. root_key.sign_writecap(&mut root_writecap)?;
  1901. let node_principal = NODE_CREDS.principal();
  1902. let writecap = make_writecap_trusted_by(
  1903. root_writecap,
  1904. &root_key,
  1905. node_principal,
  1906. vec!["apps", "contacts"],
  1907. );
  1908. let result = writecap.assert_valid_for(&writecap.body.path);
  1909. assert_authz_err(WritecapAuthzErr::NotChained, result)
  1910. }
  1911. #[test]
  1912. fn verify_writecap_invalid_root_doesnt_own_path() -> Result<()> {
  1913. let (mut root_writecap, root_key) = make_self_signed_writecap();
  1914. let owner = Principal(VarHash::from(HashKind::Sha2_256));
  1915. root_writecap.body.path = make_path_with_root(owner, vec![]);
  1916. root_key.sign_writecap(&mut root_writecap)?;
  1917. let node_principal = NODE_CREDS.principal();
  1918. let writecap = make_writecap_trusted_by(
  1919. root_writecap,
  1920. &root_key,
  1921. node_principal,
  1922. vec!["apps", "contacts"],
  1923. );
  1924. let result = writecap.assert_valid_for(&writecap.body.path);
  1925. assert_authz_err(WritecapAuthzErr::RootDoesNotOwnPath, result)
  1926. }
  1927. #[test]
  1928. fn aeadkey_encrypt_decrypt_aes256gcm() {
  1929. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  1930. let aad = [1u8; 16];
  1931. let expected = [2u8; 32];
  1932. let tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  1933. let actual = key.decrypt(&tagged).expect("decrypt failed");
  1934. assert_eq!(expected, actual.as_slice());
  1935. }
  1936. #[test]
  1937. fn aeadkey_decrypt_fails_when_ct_modified() {
  1938. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  1939. let aad = [1u8; 16];
  1940. let expected = [2u8; 32];
  1941. let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  1942. tagged.ciphertext.data[0] = tagged.ciphertext.data[0].wrapping_add(1);
  1943. let result = key.decrypt(&tagged);
  1944. assert!(result.is_err())
  1945. }
  1946. #[test]
  1947. fn aeadkey_decrypt_fails_when_aad_modified() {
  1948. let key = AeadKey::new(AeadKeyKind::AesGcm256).expect("failed to create key");
  1949. let aad = [1u8; 16];
  1950. let expected = [2u8; 32];
  1951. let mut tagged = key.encrypt(aad, &expected).expect("encrypt failed");
  1952. tagged.aad[0] = tagged.aad[0].wrapping_add(1);
  1953. let result = key.decrypt(&tagged);
  1954. assert!(result.is_err())
  1955. }
  1956. #[test]
  1957. fn compose_merkle_and_secret_streams() {
  1958. use merkle_stream::tests::make_merkle_stream_filled_with_zeros;
  1959. const SECT_SZ: usize = 4096;
  1960. const SECT_CT: usize = 16;
  1961. let merkle = make_merkle_stream_filled_with_zeros(SECT_SZ, SECT_CT);
  1962. let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
  1963. let mut secret = SecretStream::new(key)
  1964. .try_compose(merkle)
  1965. .expect("compose for secret failed");
  1966. let secret_sect_sz = secret.sector_sz();
  1967. write_fill(&mut secret, secret_sect_sz, SECT_CT);
  1968. secret.seek(SeekFrom::Start(0)).expect("seek failed");
  1969. read_check(&mut secret, secret_sect_sz, SECT_CT);
  1970. }
  1971. #[test]
  1972. fn compress_then_encrypt() {
  1973. use brotli::{CompressorWriter, Decompressor};
  1974. const SECT_SZ: usize = 4096;
  1975. const SECT_CT: usize = 16;
  1976. let params = BrotliParams::new(SECT_SZ, 8, 20);
  1977. let key = SymKey::generate(SymKeyKind::Aes256Cbc).expect("key generation failed");
  1978. let mut inner = SectoredBuf::new()
  1979. .try_compose(
  1980. SecretStream::new(key)
  1981. .try_compose(SectoredCursor::new(Vec::new(), SECT_SZ))
  1982. .expect("compose for inner failed"),
  1983. )
  1984. .expect("compose with sectored buffer failed");
  1985. {
  1986. let write: CompressorWriter<_> = params
  1987. .clone()
  1988. .try_compose(&mut inner)
  1989. .expect("compose for write failed");
  1990. write_fill(write, SECT_SZ, SECT_CT);
  1991. }
  1992. inner.seek(SeekFrom::Start(0)).expect("seek failed");
  1993. {
  1994. let read: Decompressor<_> = params
  1995. .try_compose(&mut inner)
  1996. .expect("compose for read failed");
  1997. read_check(read, SECT_SZ, SECT_CT);
  1998. }
  1999. }
  2000. fn ossl_hash_op_same_as_digest_test_case<H: Hash + From<DigestBytes>>(kind: HashKind) {
  2001. let parts = (0u8..32).map(|k| vec![k; kind.len()]).collect::<Vec<_>>();
  2002. let expected = {
  2003. let mut expected = vec![0u8; kind.len()];
  2004. kind.digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2005. .unwrap();
  2006. expected
  2007. };
  2008. let mut op = OsslHashOp::<H>::init(kind).unwrap();
  2009. for part in parts.iter() {
  2010. op.update(part.as_slice()).unwrap();
  2011. }
  2012. let actual = op.finish().unwrap();
  2013. assert_eq!(expected.as_slice(), actual.as_ref());
  2014. }
  2015. /// Tests that the hash computed using an `OsslHashOp` is the same as the one returned by the
  2016. /// `HashKind::digest` method.
  2017. #[test]
  2018. fn ossl_hash_op_same_as_digest() {
  2019. ossl_hash_op_same_as_digest_test_case::<Sha2_256>(Sha2_256::KIND);
  2020. ossl_hash_op_same_as_digest_test_case::<Sha2_512>(Sha2_512::KIND);
  2021. }
  2022. /// Tests that a `HashWrap` instance calculates the same hash as a call to the `digest` method.
  2023. #[test]
  2024. fn hash_stream_agrees_with_digest_method() {
  2025. let cursor = BtCursor::new([0u8; 3 * 32]);
  2026. let parts = (1u8..4).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
  2027. let expected = {
  2028. let mut expected = Sha2_512::default();
  2029. HashKind::Sha2_512
  2030. .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2031. .unwrap();
  2032. expected
  2033. };
  2034. let op = OsslHashOp::<Sha2_512>::init(Sha2_512::KIND).unwrap();
  2035. let mut wrap = HashStream::new(cursor, op);
  2036. for part in parts.iter() {
  2037. wrap.write(part.as_slice()).unwrap();
  2038. }
  2039. let actual = wrap.finish().unwrap();
  2040. assert_eq!(expected, actual);
  2041. }
  2042. /// Tests that the `VarHash` computed by `VarHashOp` is the same as the one returned by the
  2043. /// `digest` method.
  2044. #[test]
  2045. fn var_hash_op_agress_with_digest_method() {
  2046. let parts = (32..64u8).map(|k| [k; Sha2_512::LEN]).collect::<Vec<_>>();
  2047. let expected = {
  2048. let mut expected = VarHash::from(HashKind::Sha2_512);
  2049. HashKind::Sha2_512
  2050. .digest(expected.as_mut(), parts.iter().map(|a| a.as_slice()))
  2051. .unwrap();
  2052. expected
  2053. };
  2054. let mut op = VarHashOp::init(HashKind::Sha2_512).unwrap();
  2055. for part in parts.iter() {
  2056. op.update(part.as_slice()).unwrap();
  2057. }
  2058. let actual = op.finish().unwrap();
  2059. assert_eq!(expected, actual);
  2060. }
  2061. /// Tests that the signature produced by `OsslSignOp` can be verified.
  2062. #[test]
  2063. fn ossl_sign_op_sig_can_be_verified() {
  2064. let keys = &test_helpers::NODE_CREDS;
  2065. let part_values = (1..9u8).map(|k| [k; 32]).collect::<Vec<_>>();
  2066. let get_parts = || part_values.iter().map(|a| a.as_slice());
  2067. let mut sign_op = keys.init_sign().expect("init_sign failed");
  2068. for part in get_parts() {
  2069. sign_op.update(part).expect("update failed");
  2070. }
  2071. let sig = sign_op.finish().expect("finish failed");
  2072. keys.verify(get_parts(), sig.as_ref())
  2073. .expect("verify failed");
  2074. }
  2075. /// Tests that the signature produced by a `SignWrite` can be verified.
  2076. #[test]
  2077. fn sign_write_sig_can_be_verified() {
  2078. use crate::Decompose;
  2079. const LEN: usize = 512;
  2080. let cursor = BtCursor::new([0u8; LEN]);
  2081. let keys = &test_helpers::NODE_CREDS;
  2082. let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
  2083. let mut sign_write = SignWrite::new(cursor, sign_op);
  2084. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  2085. sign_write.write(part.as_slice()).expect("write failed");
  2086. }
  2087. let (sig, cursor) = sign_write.finish().expect("finish failed");
  2088. let array = cursor.into_inner();
  2089. keys.verify(std::iter::once(array.as_slice()), sig.as_ref())
  2090. .expect("verify failed");
  2091. }
  2092. /// Tests that data signed using a `SignWrite` can later be verified using a `VerifyRead`.
  2093. #[test]
  2094. fn sign_write_then_verify_read() {
  2095. const LEN: usize = 512;
  2096. let cursor = BtCursor::new([0u8; LEN]);
  2097. let keys = &test_helpers::NODE_CREDS;
  2098. let sign_op = keys.sign.private.init_sign().expect("init_sign failed");
  2099. let mut sign_write = SignWrite::new(cursor, sign_op);
  2100. for part in (1..9u8).map(|k| [k; LEN / 8]) {
  2101. sign_write.write(part.as_slice()).expect("write failed");
  2102. }
  2103. let (sig, mut cursor) = sign_write.finish().expect("finish failed");
  2104. cursor.seek(SeekFrom::Start(0)).expect("seek failed");
  2105. let verify_op = keys.sign.public.init_verify().expect("init_verify failed");
  2106. let mut verify_read = VerifyRead::new(cursor, verify_op);
  2107. let mut buf = Vec::with_capacity(LEN);
  2108. verify_read
  2109. .read_to_end(&mut buf)
  2110. .expect("read_to_end failed");
  2111. verify_read
  2112. .finish(sig.as_ref())
  2113. .expect("failed to verify signature");
  2114. }
  2115. /// Tests that validate the dependencies of this module.
  2116. mod dependency_tests {
  2117. use super::*;
  2118. use openssl::{
  2119. ec::{EcGroup, EcKey},
  2120. nid::Nid,
  2121. };
  2122. /// This test validates that data encrypted with AES 256 CBC can later be decrypted.
  2123. #[test]
  2124. fn aes_256_cbc_roundtrip() {
  2125. use super::*;
  2126. let expected = b"We attack at the crack of noon!";
  2127. let cipher = Cipher::aes_256_cbc();
  2128. let key = BLOCK_KEY.key_slice();
  2129. let iv = BLOCK_KEY.iv_slice();
  2130. let ciphertext = openssl_encrypt(cipher, key, iv, expected).unwrap();
  2131. let actual = openssl_decrypt(cipher, key, iv, ciphertext.as_slice()).unwrap();
  2132. assert_eq!(expected, actual.as_slice());
  2133. }
  2134. /// Tests that the keys for the SECP256K1 curve are the expected sizes.
  2135. #[test]
  2136. fn secp256k1_key_lengths() {
  2137. let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap();
  2138. let key = EcKey::generate(&group).unwrap();
  2139. let public = key.public_key_to_der().unwrap();
  2140. let private = key.private_key_to_der().unwrap();
  2141. let public_len = public.len();
  2142. let private_len = private.len();
  2143. assert_eq!(88, public_len);
  2144. assert_eq!(118, private_len);
  2145. }
  2146. #[test]
  2147. fn ed25519_key_lengths() {
  2148. let key = PKey::generate_x25519().unwrap();
  2149. let public = key.public_key_to_der().unwrap();
  2150. let private = key.private_key_to_der().unwrap();
  2151. let public_len = public.len();
  2152. let private_len = private.len();
  2153. assert_eq!(44, public_len);
  2154. assert_eq!(48, private_len);
  2155. }
  2156. }
  2157. }