mod.rs 72 KB

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