crypto.rs 75 KB

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