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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//#![allow(dead_code)]
#![no_std]

use rand;

mod hash;
use hash::{byte_array, hash_f, prf};

/// The message length as well as the length of a private key, public key, or signature element in bytes.
const N: usize = 32;
/// The Winternitz parameter; it is a member of the set {4, 16}.
const W: usize = 16;
const LOG_W: usize = 4;
/// L1 = ceil(8N / lg(W))
const L1: usize = 64;
/// L2 = floor(lg(L1 * (W - 1)) / lg(W)) + 1
const L2: usize = 3;
/// The number of N-byte string elements in a WOTS+ private key, public key, and signature.
const LEN: usize = L1 + L2;

/// The key seed for both secrey key and public key
#[derive(Clone, Copy, Default, Debug)]
pub struct Seed([u8; N]);

impl Seed {
    pub fn new() -> Self {
        Self(rand::random())
    }
}

/// The address to randomize each hash function call to prevent multi-target attacks on the used hash function.
#[derive(Clone, Copy, Default, Debug)]
pub struct Adrs([u8; 32]);

impl Adrs {
    pub fn new() -> Self {
        Self(rand::random())
    }

    /// Set the chain field of a WOTS+ address to the given value.
    pub fn set_chain(&mut self, c: u32) {
        unsafe {
            self.0.as_mut_ptr().offset(20).copy_from(c as *mut u8, 4);
        }
    }

    /// Set the hash field of a WOTS+ address to the given value.
    pub fn set_hash(&mut self, h: u32) {
        unsafe {
            self.0.as_mut_ptr().offset(24).copy_from(h as *mut u8, 4);
        }
    }

    /// Set the keymask field of a WOTS+ address to the given value.
    pub fn set_keymask(&mut self, b: u32) {
        unsafe {
            self.0.as_mut_ptr().offset(28).copy_from(b as *mut u8, 4);
        }
    }
}

/// WOTS+ private key that hasn't expanded yet. It contain a seed to derive and an address for the key pair
#[derive(Clone, Default)]
pub struct SecKey {
    seed: Seed,
    address: Adrs,
}

/// WOTS+ signature
#[derive(Clone, Copy)]
pub struct Signature {
    inner: [u8; N * LEN],
    pub_seed: Seed,
    address: Adrs,
}

impl SecKey {
    pub fn new() -> Self {
        Self {
            seed: Seed::new(),
            address: Adrs::new(),
        }
    }

    pub fn set_seed(&mut self, seed: Seed) {
        self.seed = seed;
    }

    pub fn set_address(&mut self, address: Adrs) {
        self.address = address;
    }

    /// Takes a n-byte message and the 32-byte seed for the private key to compute and return a signature.
    pub fn sign(&self, pub_seed: &Seed, msg: &[u8; N]) -> Signature {
        let lengths = concatenation(msg);
        let mut address = self.address;
        let mut sig = Signature {
            inner: [0; N * LEN],
            pub_seed: *pub_seed,
            address: self.address,
        };

        for (i, n) in lengths.iter().enumerate() {
            address.set_chain(i as u32);
            chain(
                &mut sig.inner[(i * N)..(i * N + N)],
                &prf(&self.seed.0, &address.0), // i-th secret key
                0,
                *n as usize,
                pub_seed,
                &mut address,
            );
        }

        sig
    }
}

/// WOTS+ public key
#[derive(Clone)]
pub struct PubKey {
    inner: [u8; N * LEN],
    pub_seed: Seed,
    address: Adrs,
}

impl PubKey {
    /// WOTS public key generation. Takes a 32 byte seed for the private key, expands it to
    /// a full WOTS private key and computes the corresponding public key.
    /// It requires the private key and a pub_seed (used to generate bitmasks and hash keys).
    pub fn from_seckey(seckey: &SecKey, pub_seed: &Seed) -> Self {
        let mut pubkey = Self {
            inner: [0; N * LEN],
            pub_seed: *pub_seed,
            address: seckey.address,
        };

        let mut address = seckey.address;
        for i in 0..LEN {
            address.set_chain(i as u32);
            chain(
                &mut pubkey.inner[(i * N)..(i * N + N)],
                &prf(&seckey.seed.0, &address.0), // i-th secret key
                0,
                W - 1,
                pub_seed,
                &mut address,
            );
        }

        pubkey
    }

    pub fn from_signature(sig: &Signature, msg: &[u8; N]) -> Self {
        let lengths = concatenation(msg);
        let mut address = sig.address;
        let mut pubkey = Self {
            inner: [0; N * LEN],
            pub_seed: sig.pub_seed,
            address: sig.address,
        };

        for (i, n) in lengths.iter().enumerate() {
            chain(
                &mut pubkey.inner[(i * N)..(i * N + N)],
                &sig.inner[(i * N)..(i * N + N)],
                *n as usize,
                W - 1 - *n as usize,
                &sig.pub_seed,
                &mut address,
            );
        }

        pubkey
    }
}

/// Computes the chaining function.
/// output and input have to be N-byte arrays.
/// Interprets input as start-th value of the chain.
/// address has to contain the address of the chain.
fn chain(
    output: &mut [u8],
    input: &[u8],
    start: usize,
    steps: usize,
    pub_seed: &Seed,
    address: &mut Adrs,
) {
    for i in start..(start + steps) {
        if i < W {
            address.set_hash(0);
            address.set_keymask(0);
            let key = prf(&pub_seed.0, &address.0);
            address.set_keymask(1);
            let mut bitmask = prf(&pub_seed.0, &address.0);
            for i in 0..N {
                bitmask[i] = input[i] ^ bitmask[i];
            }
            output.copy_from_slice(&hash_f(&key, &bitmask));
        }
    }
}

/// Concatenation of the base-`W` representations of the message and its checksum.
fn concatenation(msg: &[u8; N]) -> [u8; LEN] {
    let mut output = [0u8; LEN];

    // Compute base-`W` representations of the message
    base_w(&mut output[0..L1], msg);

    // Computes checksum
    let mut csum = output[0..L1]
        .iter()
        .fold(0, |acc, &x| acc + W - 1 - x as usize);

    // Convert checksum to base_w.
    // Make sure expected empty zero bits are the least significant bits.
    csum = csum << (8 - ((L2 * LOG_W) % 8));
    let mut csum_bytes = [0u8; ((L2 * LOG_W) + 7) / 8];
    byte_array(&mut csum_bytes, csum);
    base_w(&mut output[L1..LEN], &csum_bytes);

    output
}

/// base_w algorithm as described in draft.
/// Interprets an array of bytes as integers in base w.
/// This only works when log_w is a divisor of 8.
fn base_w(output: &mut [u8], input: &[u8]) {
    let mut i = 0;
    let mut bits = 0;
    let mut total: u8 = 0;
    for out in output.iter_mut() {
        if bits == 0 {
            total = input[i];
            i += 1;
            bits += 8;
        }
        bits -= LOG_W;
        *out = (total >> bits) & (W - 1) as u8;
    }
}