mod.rs 71 KB

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