mod.rs 71 KB

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