1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
//! IND-ID-CCA2 secure IBKEM by a scheme by Chen, Gay and Wee.
//! * From: "[Improved Dual System ABE in Prime-Order Groups via Predicate Encodings](https://link.springer.com/chapter/10.1007/978-3-540-79263-5_14)"
//!
//! CCA security due to a general approach by Fujisaki and Okamoto.
//! * From: "[A Modular Analysis of the Fujisaki-Okamoto Transformation](https://eprint.iacr.org/2017/604.pdf)"
//!
//! Symmetric primitives G and H instantiated using sha3_512 and sha3_256, respectively.
//! To output a bigger secret SHAKE256 can be used with a bigger output buffer.
//!
//! A drawback of a Fujisaki-Okamoto transform is that we now need the public key to decapsulate.

use crate::ibe::cgw::{CipherText, Msg, CGW, USK_BYTES as CPA_USK_BYTES};
use crate::ibe::IBE;
use crate::kem::{Error, SharedSecret, IBKEM};
use crate::util::*;
use crate::Compress;
use arrayref::{array_refs, mut_array_refs};
use group::Group;
use rand::{CryptoRng, Rng};
use subtle::{ConstantTimeEq, CtOption};

/// These struct are identical for the CCA KEM.
pub use crate::ibe::cgw::{PublicKey, SecretKey, CT_BYTES, MSG_BYTES, PK_BYTES, SK_BYTES};

/// Size of the compressed user secret key in bytes.
///
/// The USK includes a random message and the identity (needed for re-encryption).
pub const USK_BYTES: usize = CPA_USK_BYTES + ID_BYTES;

/// User secret key. Can be used to decaps the corresponding ciphertext.
/// Also known as USK_{id}.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct UserSecretKey {
    usk: crate::ibe::cgw::UserSecretKey,
    id: Identity,
}

impl Compress for UserSecretKey {
    const OUTPUT_SIZE: usize = USK_BYTES;
    type Output = [u8; Self::OUTPUT_SIZE];

    fn to_bytes(&self) -> [u8; USK_BYTES] {
        let mut buf = [0u8; USK_BYTES];
        let (usk, id) = mut_array_refs![&mut buf, CPA_USK_BYTES, ID_BYTES];

        *usk = self.usk.to_bytes();
        id.copy_from_slice(&self.id.0);

        buf
    }

    fn from_bytes(bytes: &[u8; USK_BYTES]) -> CtOption<Self> {
        let (usk, rid) = array_refs![&bytes, CPA_USK_BYTES, ID_BYTES];

        let usk = crate::ibe::cgw::UserSecretKey::from_bytes(usk);
        let id = Identity(*rid);

        usk.map(|usk| UserSecretKey { usk, id })
    }
}

/// The CCA2 secure KEM that results by applying the implicit rejection
/// variant of the Fujisaki-Okamoto transform to the Chen-Gay-Wee IBE scheme.
#[derive(Debug, Clone, Copy)]
pub struct CGWFO;

impl IBKEM for CGWFO {
    const IDENTIFIER: &'static str = "cgwfo";

    type Pk = PublicKey;
    type Sk = SecretKey;
    type Usk = UserSecretKey;
    type Ct = CipherText;
    type Id = Identity;

    const PK_BYTES: usize = PK_BYTES;
    const USK_BYTES: usize = USK_BYTES;
    const SK_BYTES: usize = SK_BYTES;
    const CT_BYTES: usize = CT_BYTES;

    fn setup<R: Rng + CryptoRng>(rng: &mut R) -> (PublicKey, SecretKey) {
        CGW::setup(rng)
    }

    fn extract_usk<R: Rng + CryptoRng>(
        _pk: Option<&PublicKey>,
        sk: &SecretKey,
        id: &Identity,
        rng: &mut R,
    ) -> UserSecretKey {
        let usk = CGW::extract_usk(None, sk, id, rng);

        UserSecretKey { usk, id: *id }
    }

    fn encaps<R: Rng + CryptoRng>(
        pk: &PublicKey,
        id: &Identity,
        rng: &mut R,
    ) -> (CipherText, SharedSecret) {
        let m = Msg::random(rng);

        let mut pre_coins = [0u8; MSG_BYTES + ID_BYTES];
        pre_coins[..MSG_BYTES].copy_from_slice(&m.to_bytes());

        pre_coins[MSG_BYTES..].copy_from_slice(&id.0);
        let coins = sha3_512(&pre_coins);

        let ct = CGW::encrypt(pk, id, &m, &coins);

        (ct, SharedSecret::from(&m))
    }

    /// Decapsulate a shared secret from the ciphertext.
    ///
    /// # Panics
    ///
    /// This scheme **does** requires the master public key due to usage the Fujisaki-Okamoto transform.
    /// This function panics if no master public key is provided.
    ///
    /// # Errors
    ///
    /// This function returns an [`Error`] when an illegitimate ciphertext is encountered (explicit rejection).
    fn decaps(
        opk: Option<&PublicKey>,
        usk: &UserSecretKey,
        c: &CipherText,
    ) -> Result<SharedSecret, Error> {
        let pk = opk.unwrap();

        let m = CGW::decrypt(&usk.usk, c);

        let mut pre_coins = [0u8; MSG_BYTES + ID_BYTES];
        pre_coins[..MSG_BYTES].copy_from_slice(&m.to_bytes());
        pre_coins[MSG_BYTES..].copy_from_slice(&usk.id.0);

        let coins = sha3_512(&pre_coins);

        let c2 = CGW::encrypt(pk, &usk.id, &m, &coins);

        // Can save some time by not doing a constant-time comparison
        // since we can leak whether the decapsulation succeeds/fails.
        if c.ct_eq(&c2).into() {
            Ok(SharedSecret::from(&m))
        } else {
            Err(Error)
        }
    }
}

#[cfg(feature = "mkem")]
impl crate::kem::mkem::MultiRecipient for CGWFO {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Derive;

    test_kem!(CGWFO);

    #[cfg(feature = "mkem")]
    test_multi_kem!(CGWFO);
}