Skip to main content

picnic_bindings/
lib.rs

1//! # Bindings for Picnic: Post-Quantum Signatures
2//!
3//! The Picnic signature scheme is a family of digital signature schemes secure against attacks by
4//! quantum computers. This crate provides bindings that implements the traits from the [signature]
5//! crate.
6//!
7//! More information on Picnic is available on the project website:
8//! <https://microsoft.github.io/Picnic/>
9//!
10//! Serialization and deserialization is implemented via the `serde` crate. By enabling the
11//! `serialization` feature, all public structs implement the `Serialize` and `Deserialize` traits.
12//!
13//! ## Usage
14//!
15//! Key generation, signing and verification can be implemented as follows:
16//! ```
17//! # #[cfg(feature="picnic")] {
18//! use picnic_bindings::{PicnicL1FSSigningKey, Signer, Verifier};
19//!
20//! let (signing_key, verification_key) = PicnicL1FSSigningKey::random().expect("Key generation failed");
21//! let msg = "some message".as_bytes();
22//! let signature = signing_key.sign(msg);
23//! verification_key.verify(msg, &signature).expect("Verification failed");
24//! # }
25//! ```
26//!
27//! Keys and signatures support conversions to and from `&[u8]`. The following code example
28//! demonstrates the necessary steps for [SigningKey]:
29//! ```
30//! # #[cfg(feature="picnic")] {
31//! use picnic_bindings::{PicnicL1FSSigningKey};
32//!
33//! let (signing_key, verification_key) = PicnicL1FSSigningKey::random().expect("Key generation failed");
34//! let signing_key_2 = PicnicL1FSSigningKey::try_from(signing_key.as_ref()).expect("Deserialization failed");
35//! assert_eq!(signing_key, signing_key_2);
36//! # }
37//! ```
38//!
39//! Alternatively:
40//! ```
41//! # #[cfg(feature="picnic")] {
42//! use picnic_bindings::{DynamicSigningKey, PicnicL1FS, Parameters, Signer, Verifier};
43//!
44//! let (signing_key, verification_key) = DynamicSigningKey::random(PicnicL1FS::PARAM).expect("Key generation failed");
45//! let msg = "some message".as_bytes();
46//! let signature = signing_key.sign(msg);
47//! verification_key.verify(msg, &signature).expect("Verification failed");
48//! # }
49//! ```
50//!
51//! In case a signature as only available as `&[u8]` and taking ownership is not desired, the
52//! [RawVerifier] trait offers a method to verify the signature without first converting it into an
53//! instance of [DynamicSignature].
54//! ```
55//! # #[cfg(feature="picnic")] {
56//! use picnic_bindings::{PicnicL1FSSigningKey, Signer, RawVerifier};
57//!
58//! let (signing_key, verification_key) = PicnicL1FSSigningKey::random().expect("Key generation failed");
59//! let msg = "some message".as_bytes();
60//! let signature = signing_key.sign(msg);
61//! // assume that this is the actual signature
62//! let signature = signature.as_ref();
63//! verification_key.verify_raw(msg, signature).expect("Verification failed");
64//! # }
65//! ```
66
67#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
68#![warn(missing_docs)]
69
70// If neither is specified, the crate is essentially empty.
71#[cfg(all(not(feature = "picnic"), not(feature = "picnic3")))]
72compile_error!("One of the features \"picnic\" and \"picnic3\" is required.");
73
74#[cfg(not(feature = "std"))]
75extern crate alloc;
76
77#[cfg(not(feature = "std"))]
78use alloc::{format, vec, vec::Vec};
79
80use core::fmt::{self, Debug};
81use core::marker::PhantomData;
82use libpicnic_sys::*;
83use pastey::paste;
84pub use signature::{self, Error, Signer, Verifier};
85
86#[cfg(feature = "serialization")]
87use serde::{Deserialize, Deserializer, Serialize, Serializer};
88
89#[cfg(feature = "zeroize")]
90use zeroize::{Zeroize, ZeroizeOnDrop};
91
92#[cfg(feature = "subtle")]
93use subtle::{Choice, ConstantTimeEq};
94
95mod wrapper;
96use crate::wrapper::*;
97
98#[cfg(feature = "serialization")]
99mod serialization;
100
101#[cfg(feature = "serialization")]
102use serialization::{deserialize, serialize};
103
104/// Trait to describe Picnic parameters
105pub trait Parameters: Clone {
106    /// Internal parameter
107    const PARAM: picnic_params_t;
108    /// Max size of a signature
109    const MAX_SIGNATURE_SIZE: usize;
110    /// Size of the serialized private key
111    const PRIVATE_KEY_SIZE: usize;
112    /// Size of the serialized public key
113    const PUBLIC_KEY_SIZE: usize;
114
115    /// Retrieve name of the parameter set
116    fn parameter_name() -> &'static str;
117}
118
119/// Trait that allows to directly verify a signature from a `&[u8]`
120///
121/// With this trait verifiers are able to verify a signature without first storing it in a
122/// [DynamicSignature] to satisfy the [Verifier] interface.
123pub trait RawVerifier {
124    /// Verify a "raw" signature.
125    fn verify_raw(&self, msg: &[u8], signature: &[u8]) -> Result<(), Error>;
126}
127
128/// Define a parameters set and its associated implementations and types
129macro_rules! define_params {
130    ($name:ident, $param:ident) => {
131        paste! {
132            #[doc = $name " parameters"]
133            #[derive(Clone, Debug, PartialEq, Eq)]
134            #[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
135            pub struct $name {}
136
137            impl Parameters for $name {
138                const PARAM: picnic_params_t = picnic_params_t::$param;
139                const MAX_SIGNATURE_SIZE: usize = [<PICNIC_SIGNATURE_SIZE_ $param>];
140                const PRIVATE_KEY_SIZE: usize = [<PICNIC_PRIVATE_KEY_SIZE_ $param>];
141                const PUBLIC_KEY_SIZE: usize = [<PICNIC_PUBLIC_KEY_SIZE_ $param>];
142
143                #[inline(always)]
144                fn parameter_name() -> &'static str {
145                    "$param"
146                }
147            }
148
149            #[doc = "Signing key for " $name]
150            pub type [<$name SigningKey>] = SigningKey<$name>;
151            #[doc = "Verification key for " $name]
152            pub type [<$name VerificationKey>] = VerificationKey<$name>;
153        }
154    };
155}
156
157#[cfg(feature = "picnic")]
158define_params!(PicnicL1FS, Picnic_L1_FS);
159#[cfg(feature = "unruh-transform")]
160define_params!(PicnicL1UR, Picnic_L1_UR);
161#[cfg(feature = "picnic")]
162define_params!(PicnicL1Full, Picnic_L1_full);
163#[cfg(feature = "picnic3")]
164define_params!(Picnic3L1, Picnic3_L1);
165
166#[cfg(feature = "picnic")]
167define_params!(PicnicL3FS, Picnic_L3_FS);
168#[cfg(feature = "unruh-transform")]
169define_params!(PicnicL3UR, Picnic_L3_UR);
170#[cfg(feature = "picnic")]
171define_params!(PicnicL3Full, Picnic_L3_full);
172#[cfg(feature = "picnic3")]
173define_params!(Picnic3L3, Picnic3_L3);
174
175#[cfg(feature = "picnic")]
176define_params!(PicnicL5FS, Picnic_L5_FS);
177#[cfg(feature = "unruh-transform")]
178define_params!(PicnicL5UR, Picnic_L5_UR);
179#[cfg(feature = "picnic")]
180define_params!(PicnicL5Full, Picnic_L5_full);
181#[cfg(feature = "picnic3")]
182define_params!(Picnic3L5, Picnic3_L5);
183
184/// Signature stored in a `Vec`
185///
186/// While storing signatures in arrays is possible, their size varies even for the same parameter
187/// set.
188#[derive(Debug, Clone, Eq, PartialEq)]
189#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
190pub struct DynamicSignature(
191    #[cfg_attr(feature = "serialization", serde(with = "serde_bytes"))] Vec<u8>,
192);
193
194impl AsRef<[u8]> for DynamicSignature {
195    fn as_ref(&self) -> &[u8] {
196        self.0.as_ref()
197    }
198}
199
200impl From<&[u8]> for DynamicSignature {
201    fn from(bytes: &[u8]) -> Self {
202        Self(bytes.into())
203    }
204}
205
206/// Signing key generic over the parameters
207#[derive(Clone)]
208#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
209pub struct SigningKey<P: Parameters> {
210    data: PrivateKey,
211    #[cfg_attr(feature = "zeroize", zeroize(skip))]
212    phantom_data: PhantomData<P>,
213}
214
215impl<P> SigningKey<P>
216where
217    P: Parameters,
218{
219    /// Sample a new random signing key and the corresponding verification key.
220    /// This operation may fail if the Picnic library is not built with support
221    /// for the given parameter set.
222    pub fn random() -> Result<(Self, VerificationKey<P>), Error> {
223        PrivateKey::random(P::PARAM).map(|(sk, vk)| {
224            (
225                Self {
226                    data: sk,
227                    phantom_data: PhantomData,
228                },
229                VerificationKey {
230                    data: vk,
231                    phantom_data: PhantomData,
232                },
233            )
234        })
235    }
236}
237
238impl<P> Signer<DynamicSignature> for SigningKey<P>
239where
240    P: Parameters,
241{
242    fn try_sign(&self, msg: &[u8]) -> Result<DynamicSignature, Error> {
243        let mut signature = vec![0; P::MAX_SIGNATURE_SIZE];
244
245        let length = self.data.try_sign(msg, signature.as_mut_slice())?;
246        signature.resize(length, 0);
247        Ok(DynamicSignature(signature))
248    }
249}
250
251impl<P> Verifier<DynamicSignature> for SigningKey<P>
252where
253    P: Parameters,
254{
255    fn verify(&self, msg: &[u8], signature: &DynamicSignature) -> Result<(), Error> {
256        self.data
257            .public_key()
258            .and_then(|pk| pk.verify(msg, signature.as_ref()))
259    }
260}
261
262impl<P> PicnicKey for SigningKey<P>
263where
264    P: Parameters,
265{
266    #[inline(always)]
267    fn param(&self) -> picnic_params_t {
268        P::PARAM
269    }
270
271    #[inline(always)]
272    fn serialized_size(&self) -> usize {
273        P::PRIVATE_KEY_SIZE
274    }
275}
276
277impl<P> AsRef<[u8]> for SigningKey<P>
278where
279    P: Parameters,
280{
281    fn as_ref(&self) -> &[u8] {
282        // FIXME: this breaks the abstraction layer; this should be a call to picnic_write_private_key
283        &self.data.as_ref().data[0..P::PRIVATE_KEY_SIZE]
284    }
285}
286
287impl<P> TryFrom<&[u8]> for SigningKey<P>
288where
289    P: Parameters,
290{
291    type Error = Error;
292
293    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
294        let sk = PrivateKey::try_from(value)?;
295        match sk.param() == P::PARAM {
296            true => Ok(Self {
297                data: sk,
298                phantom_data: PhantomData,
299            }),
300            false => Err(Self::Error::new()),
301        }
302    }
303}
304
305impl<P> Debug for SigningKey<P>
306where
307    P: Parameters,
308{
309    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
310        fmt.debug_struct(&format!("SigningKey<{}>", P::parameter_name()))
311            .field("data", &"[...]")
312            .finish()
313    }
314}
315
316impl<P> PartialEq for SigningKey<P>
317where
318    P: Parameters,
319{
320    fn eq(&self, other: &Self) -> bool {
321        self.as_ref() == other.as_ref()
322    }
323}
324
325impl<P> Eq for SigningKey<P> where P: Parameters {}
326
327#[cfg(feature = "subtle")]
328impl<P> ConstantTimeEq for SigningKey<P>
329where
330    P: Parameters,
331{
332    fn ct_eq(&self, other: &Self) -> Choice {
333        self.as_ref().ct_eq(other.as_ref())
334    }
335}
336
337#[cfg(feature = "serialization")]
338impl<P> Serialize for SigningKey<P>
339where
340    P: Parameters,
341{
342    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
343    where
344        S: Serializer,
345    {
346        serialize(self, serializer)
347    }
348}
349
350#[cfg(feature = "serialization")]
351impl<'de, P> Deserialize<'de> for SigningKey<P>
352where
353    P: Parameters,
354{
355    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
356    where
357        D: Deserializer<'de>,
358    {
359        deserialize(deserializer)
360    }
361}
362
363/// Verification key generic over the parameters
364#[derive(Clone)]
365pub struct VerificationKey<P: Parameters> {
366    data: PublicKey,
367    phantom_data: PhantomData<P>,
368}
369
370impl<P> Verifier<DynamicSignature> for VerificationKey<P>
371where
372    P: Parameters,
373{
374    fn verify(&self, msg: &[u8], signature: &DynamicSignature) -> Result<(), Error> {
375        self.verify_raw(msg, &signature.0)
376    }
377}
378
379impl<P> RawVerifier for VerificationKey<P>
380where
381    P: Parameters,
382{
383    fn verify_raw(&self, msg: &[u8], signature: &[u8]) -> Result<(), Error> {
384        self.data.verify(msg, signature)
385    }
386}
387
388impl<P> PicnicKey for VerificationKey<P>
389where
390    P: Parameters,
391{
392    #[inline(always)]
393    fn param(&self) -> picnic_params_t {
394        P::PARAM
395    }
396
397    #[inline(always)]
398    fn serialized_size(&self) -> usize {
399        P::PUBLIC_KEY_SIZE
400    }
401}
402
403impl<P> AsRef<[u8]> for VerificationKey<P>
404where
405    P: Parameters,
406{
407    fn as_ref(&self) -> &[u8] {
408        // FIXME: this breaks the abstraction layer; this should be a call to picnic_write_public_key
409        &self.data.as_ref().data[0..P::PUBLIC_KEY_SIZE]
410    }
411}
412
413impl<P> TryFrom<&[u8]> for VerificationKey<P>
414where
415    P: Parameters,
416{
417    type Error = Error;
418
419    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
420        let vk = PublicKey::try_from(value)?;
421        match vk.param() == P::PARAM {
422            true => Ok(Self {
423                data: vk,
424                phantom_data: PhantomData,
425            }),
426            false => Err(Self::Error::new()),
427        }
428    }
429}
430
431impl<P> TryFrom<&SigningKey<P>> for VerificationKey<P>
432where
433    P: Parameters,
434{
435    type Error = Error;
436
437    fn try_from(sk: &SigningKey<P>) -> Result<Self, Self::Error> {
438        sk.data.public_key().map(|vk| Self {
439            data: vk,
440            phantom_data: PhantomData,
441        })
442    }
443}
444
445impl<P> Debug for VerificationKey<P>
446where
447    P: Parameters,
448{
449    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
450        fmt.debug_struct(&format!("VerificationKey<{}>", P::parameter_name()))
451            .field("data", &self.data)
452            .finish()
453    }
454}
455
456impl<P> PartialEq for VerificationKey<P>
457where
458    P: Parameters,
459{
460    fn eq(&self, other: &Self) -> bool {
461        self.as_ref() == other.as_ref()
462    }
463}
464
465impl<P> Eq for VerificationKey<P> where P: Parameters {}
466
467#[cfg(feature = "serialization")]
468impl<P> Serialize for VerificationKey<P>
469where
470    P: Parameters,
471{
472    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
473    where
474        S: Serializer,
475    {
476        serialize(self, serializer)
477    }
478}
479
480#[cfg(feature = "serialization")]
481impl<'de, P> Deserialize<'de> for VerificationKey<P>
482where
483    P: Parameters,
484{
485    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
486    where
487        D: Deserializer<'de>,
488    {
489        deserialize(deserializer)
490    }
491}
492
493/// Signing key
494#[derive(Clone)]
495#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
496pub struct DynamicSigningKey {
497    data: PrivateKey,
498}
499
500impl Debug for DynamicSigningKey {
501    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
502        fmt.debug_struct("DynamicSigningKey")
503            .field("param", &self.param())
504            .field("data", &"[...]")
505            .finish()
506    }
507}
508
509impl DynamicSigningKey {
510    /// Sample a new random signing key and the corresponding verification key.
511    /// This operation may fail if the Picnic library is not built with support
512    /// for the given parameter set.
513    pub fn random(params: picnic_params_t) -> Result<(Self, DynamicVerificationKey), Error> {
514        PrivateKey::random(params)
515            .map(|(sk, vk)| (Self { data: sk }, DynamicVerificationKey { data: vk }))
516    }
517}
518
519impl Signer<DynamicSignature> for DynamicSigningKey {
520    fn try_sign(&self, msg: &[u8]) -> Result<DynamicSignature, Error> {
521        let mut signature = vec![0; signature_size(self.param())];
522        let length = self.data.try_sign(msg, signature.as_mut_slice())?;
523        signature.resize(length, 0);
524        Ok(DynamicSignature(signature))
525    }
526}
527
528impl Verifier<DynamicSignature> for DynamicSigningKey {
529    fn verify(&self, msg: &[u8], signature: &DynamicSignature) -> Result<(), Error> {
530        self.data
531            .public_key()
532            .and_then(|pk| pk.verify(msg, signature.as_ref()))
533    }
534}
535
536impl PicnicKey for DynamicSigningKey {
537    #[inline(always)]
538    fn param(&self) -> picnic_params_t {
539        self.data.param()
540    }
541
542    #[inline(always)]
543    fn serialized_size(&self) -> usize {
544        self.data.serialized_size()
545    }
546}
547
548impl AsRef<[u8]> for DynamicSigningKey {
549    fn as_ref(&self) -> &[u8] {
550        // FIXME: this breaks the abstraction layer; this should be a call to picnic_write_private_key
551        &self.data.as_ref().data[0..self.serialized_size()]
552    }
553}
554
555impl TryFrom<&[u8]> for DynamicSigningKey {
556    type Error = Error;
557
558    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
559        let sk = PrivateKey::try_from(value)?;
560        match sk.param() != picnic_params_t::PARAMETER_SET_INVALID {
561            true => Ok(DynamicSigningKey { data: sk }),
562            false => Err(Self::Error::new()),
563        }
564    }
565}
566
567impl PartialEq for DynamicSigningKey {
568    fn eq(&self, other: &Self) -> bool {
569        self.param() == other.param() && {
570            let size = self.serialized_size();
571            self.data.as_ref().data[..size] == other.data.as_ref().data[..size]
572        }
573    }
574}
575
576impl Eq for DynamicSigningKey {}
577
578#[cfg(feature = "serialization")]
579impl Serialize for DynamicSigningKey {
580    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
581    where
582        S: Serializer,
583    {
584        serialize(self, serializer)
585    }
586}
587
588#[cfg(feature = "serialization")]
589impl<'de> Deserialize<'de> for DynamicSigningKey {
590    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
591    where
592        D: Deserializer<'de>,
593    {
594        deserialize(deserializer)
595    }
596}
597
598/// Verification key
599#[derive(Clone, Debug)]
600pub struct DynamicVerificationKey {
601    data: PublicKey,
602}
603
604impl Verifier<DynamicSignature> for DynamicVerificationKey {
605    fn verify(&self, msg: &[u8], signature: &DynamicSignature) -> Result<(), Error> {
606        self.verify_raw(msg, &signature.0)
607    }
608}
609
610impl RawVerifier for DynamicVerificationKey {
611    fn verify_raw(&self, msg: &[u8], signature: &[u8]) -> Result<(), Error> {
612        self.data.verify(msg, signature)
613    }
614}
615
616impl PicnicKey for DynamicVerificationKey {
617    #[inline(always)]
618    fn param(&self) -> picnic_params_t {
619        self.data.param()
620    }
621
622    #[inline(always)]
623    fn serialized_size(&self) -> usize {
624        self.data.serialized_size()
625    }
626}
627
628impl AsRef<[u8]> for DynamicVerificationKey {
629    fn as_ref(&self) -> &[u8] {
630        // FIXME: this breaks the abstraction layer; this should be a call to picnic_write_public_key
631        &self.data.as_ref().data[0..self.serialized_size()]
632    }
633}
634
635impl TryFrom<&[u8]> for DynamicVerificationKey {
636    type Error = Error;
637
638    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
639        let vk = PublicKey::try_from(value)?;
640        match vk.param() != picnic_params_t::PARAMETER_SET_INVALID {
641            true => Ok(DynamicVerificationKey { data: vk }),
642            false => Err(Self::Error::new()),
643        }
644    }
645}
646
647impl TryFrom<&DynamicSigningKey> for DynamicVerificationKey {
648    type Error = Error;
649
650    fn try_from(sk: &DynamicSigningKey) -> Result<Self, Self::Error> {
651        sk.data.public_key().map(|vk| Self { data: vk })
652    }
653}
654
655impl PartialEq for DynamicVerificationKey {
656    fn eq(&self, other: &Self) -> bool {
657        self.param() == other.param() && {
658            let size = self.serialized_size();
659            self.data.as_ref().data[..size] == other.data.as_ref().data[..size]
660        }
661    }
662}
663
664impl Eq for DynamicVerificationKey {}
665
666#[cfg(feature = "serialization")]
667impl Serialize for DynamicVerificationKey {
668    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
669    where
670        S: Serializer,
671    {
672        serialize(self, serializer)
673    }
674}
675
676#[cfg(feature = "serialization")]
677impl<'de> Deserialize<'de> for DynamicVerificationKey {
678    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
679    where
680        D: Deserializer<'de>,
681    {
682        deserialize(deserializer)
683    }
684}
685
686#[cfg(test)]
687mod test {
688    #[cfg(feature = "picnic")]
689    use crate::{PicnicL1FSSigningKey, PicnicL1FullSigningKey, PicnicL1FullVerificationKey};
690
691    #[cfg(feature = "picnic")]
692    #[test]
693    fn serialization_param_mismatch() {
694        let (sk1, vk1) = PicnicL1FSSigningKey::random().expect("unable to generate keys");
695        PicnicL1FullSigningKey::try_from(sk1.as_ref()).expect_err("deserialization did not fail");
696        PicnicL1FullVerificationKey::try_from(vk1.as_ref())
697            .expect_err("deserialization did not fail");
698    }
699}