koibumi-core 0.0.9

The core library for Koibumi, an experimental Bitmessage client
Documentation
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Provides methods to encrypt/decrypt Bitmessage messages.

use std::{
    convert::TryInto,
    fmt,
    io::{self, Read, Write},
    mem::size_of,
};

use aes::cipher::block_padding::Pkcs7;
use cbc::cipher::{
    inout::{block_padding::UnpadError, PadError},
    BlockDecryptMut, BlockEncryptMut, KeyIvInit,
};
use hmac::{digest, Mac};
use rand::Rng;

use koibumi_secp256k1 as secp256k1;

use crate::{
    error::TooLongError,
    hash::sha256,
    io::{LenBm, ReadFrom, SizedReadFrom, WriteTo},
    message,
    var_type::VarInt,
};

pub use crate::error::TooShortError;

const KEY_LEN: usize = 32;

/// This error indicates that the operation on a private key failed.
#[derive(Clone, Debug)]
pub enum PrivateKeyError {
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
}

impl fmt::Display for PrivateKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secp256k1Error(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for PrivateKeyError {}

impl From<secp256k1::Error> for PrivateKeyError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

/// A private key.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct PrivateKey {
    bytes: [u8; KEY_LEN],
}

impl PrivateKey {
    /// Constructs a private key from a byte array.
    pub fn new(bytes: [u8; KEY_LEN]) -> Result<Self, PrivateKeyError> {
        let _sk = secp256k1::SecretKey::from_slice(bytes.as_ref())?;
        Ok(Self { bytes })
    }

    /// Returns the public key derived from this private key.
    pub fn public_key(&self) -> PublicKey {
        let sk = secp256k1::SecretKey::from_slice(self.bytes.as_ref()).unwrap();
        let secp = secp256k1::Secp256k1::new();
        let pk = secp256k1::PublicKey::from_secret_key(&secp, &sk);
        let bytes = pk.serialize_uncompressed();
        let mut x = [0; KEY_LEN];
        let mut y = [0; KEY_LEN];
        x.copy_from_slice(&bytes[1..KEY_LEN + 1]);
        y.copy_from_slice(&bytes[KEY_LEN + 1..]);
        PublicKey::new(x, y).unwrap()
    }
}

impl AsRef<[u8]> for PrivateKey {
    fn as_ref(&self) -> &[u8] {
        &self.bytes
    }
}

/// This error indicates that the operation on a public key failed.
#[derive(Clone, Debug)]
pub enum PublicKeyError {
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
}

impl fmt::Display for PublicKeyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secp256k1Error(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for PublicKeyError {}

impl From<secp256k1::Error> for PublicKeyError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

/// A public key.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct PublicKey {
    x: [u8; KEY_LEN],
    y: [u8; KEY_LEN],
}

impl PublicKey {
    /// Constructs a public key from its components.
    pub fn new(x: [u8; KEY_LEN], y: [u8; KEY_LEN]) -> Result<Self, PublicKeyError> {
        let public_key = Self { x, y };
        let _pk = secp256k1::PublicKey::from_slice(&public_key.encode())?;
        Ok(public_key)
    }

    const PREFIX: u8 = 0x04;

    /// Encodes the public key.
    pub fn encode(&self) -> Vec<u8> {
        let mut encoded = Vec::with_capacity(1 + KEY_LEN + KEY_LEN);
        encoded.push(Self::PREFIX);
        encoded.extend_from_slice(&self.x);
        encoded.extend_from_slice(&self.y);
        encoded
    }
}

impl WriteTo for PublicKey {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.x.write_to(w)?;
        self.y.write_to(w)?;
        Ok(())
    }
}

impl ReadFrom for PublicKey {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let x = <[u8; KEY_LEN]>::read_from(r)?;
        let y = <[u8; KEY_LEN]>::read_from(r)?;
        Ok(Self { x, y })
    }
}

/// A pair of a public key and a private key.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct KeyPair {
    public_key: PublicKey,
    private_key: PrivateKey,
}

impl KeyPair {
    /// Returns the public key.
    pub fn public_key(&self) -> &PublicKey {
        &self.public_key
    }

    /// Returns the private key.
    pub fn private_key(&self) -> &PrivateKey {
        &self.private_key
    }

    /// Generates a random key pair.
    pub fn generate() -> Self {
        let secp = secp256k1::Secp256k1::signing_only();
        let mut rng = rand::rngs::OsRng::default();
        let (sk, pk) = secp.generate_keypair(&mut rng);

        let mut bytes = [0; KEY_LEN];
        bytes.copy_from_slice(&sk[..]);
        let private_key = PrivateKey::new(bytes).unwrap();
        let bytes = pk.serialize_uncompressed();
        let mut x = [0; KEY_LEN];
        let mut y = [0; KEY_LEN];
        x.copy_from_slice(&bytes[1..KEY_LEN + 1]);
        y.copy_from_slice(&bytes[KEY_LEN + 1..]);
        let public_key = PublicKey::new(x, y).unwrap();
        Self {
            public_key,
            private_key,
        }
    }
}

const CURVE_TYPE: u16 = 0x02ca;
type Aes256CbcEnc = cbc::Encryptor<aes::Aes256>;
type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;

/// This error indicates that the encryption failed.
#[derive(Clone, Debug)]
pub enum EncryptError {
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
    /// An error was caught during initialization of the MAC generator.
    /// The actual error caught is returned as a payload of this variant.
    InvalidMacKeyIvLength(digest::InvalidLength),
    /// Padding error.
    PadError(PadError),
}

impl fmt::Display for EncryptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secp256k1Error(err) => err.fmt(f),
            Self::InvalidMacKeyIvLength(err) => err.fmt(f),
            Self::PadError(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for EncryptError {}

impl From<secp256k1::Error> for EncryptError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

impl From<digest::InvalidLength> for EncryptError {
    fn from(err: digest::InvalidLength) -> Self {
        Self::InvalidMacKeyIvLength(err)
    }
}

impl From<PadError> for EncryptError {
    fn from(err: PadError) -> Self {
        Self::PadError(err)
    }
}

/// This error indicates
/// that the decryption failed.
#[derive(Clone, Debug)]
pub enum DecryptError {
    /// Indicates that the object was encrypted by using a curve unsupported by this implementation.
    UnsupportedCurve(u16),
    /// Indicates that at least one of the lengths of the components of the public key was invalid.
    /// The actual lengths of the components are returned as payloads of this variant.
    InvalidKeyLength {
        /// The actual length of the component x.
        x_len: usize,
        /// The actual length of the component y.
        y_len: usize,
    },
    /// An error was caught during initialization of the MAC verifier.
    /// The actual error caught is returned as a payload of this variant.
    InvalidMacKeyIvLength(digest::InvalidLength),
    /// Indicates that the secret key is invalid.
    InvalidSecretKey,
    /// An error was caught during verification of the MAC.
    /// The actual error caught is returned as a payload of this variant.
    MacError(digest::MacError),
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
    /// Unpadding error.
    UnpadError(UnpadError),
}

impl fmt::Display for DecryptError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedCurve(curve) => write!(f, "unsupported curve: {:#04x}", curve),
            Self::InvalidKeyLength { x_len, y_len } => {
                write!(f, "invalid key length x: {}, y: {}", x_len, y_len)
            }
            Self::InvalidMacKeyIvLength(err) => err.fmt(f),
            Self::InvalidSecretKey => "invalid secret key".fmt(f),
            Self::MacError(err) => err.fmt(f),
            Self::Secp256k1Error(err) => err.fmt(f),
            Self::UnpadError(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for DecryptError {}

impl From<digest::InvalidLength> for DecryptError {
    fn from(err: digest::InvalidLength) -> Self {
        Self::InvalidMacKeyIvLength(err)
    }
}

impl From<digest::MacError> for DecryptError {
    fn from(err: digest::MacError) -> Self {
        Self::MacError(err)
    }
}

impl From<secp256k1::Error> for DecryptError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

impl From<UnpadError> for DecryptError {
    fn from(err: UnpadError) -> Self {
        Self::UnpadError(err)
    }
}

const IV_LEN: usize = 16;
const MAC_LEN: usize = 32;

/// A encrypted message.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Encrypted {
    iv: [u8; IV_LEN],
    curve_type: u16,
    //x_length: u16,
    x: Vec<u8>,
    //y_length: u16,
    y: Vec<u8>,
    encrypted: Vec<u8>,
    mac: [u8; MAC_LEN],
}

impl Encrypted {
    /// Encrypts data and returns a encrypted object.
    pub fn encrypt(data: impl AsRef<[u8]>, public_key: &PublicKey) -> Result<Self, EncryptError> {
        let secp = secp256k1::Secp256k1::signing_only();
        let mut rng = rand::rngs::OsRng::default();
        let (sk, pk) = secp.generate_keypair(&mut rng);

        let bytes = pk.serialize_uncompressed();
        let mut x = [0; KEY_LEN];
        let mut y = [0; KEY_LEN];
        x.copy_from_slice(&bytes[1..KEY_LEN + 1]);
        y.copy_from_slice(&bytes[KEY_LEN + 1..]);

        let public_key = secp256k1::PublicKey::from_slice(&public_key.encode())?;

        let shared_secret =
            secp256k1::ecdh::SharedSecret::new_with_hash(&public_key, &sk, |x, _y| {
                secp256k1::ecdh::SharedSecret::from_bytes(x)
            });

        let h = crate::hash::sha512(shared_secret);
        let encryption_key = &h[..32];
        let iv: [u8; IV_LEN] = rng.gen();
        let pt_len = data.as_ref().len();
        let buf_len = (pt_len % 32) * 32;
        let buf_len = if pt_len > buf_len {
            buf_len + 32
        } else {
            buf_len
        };
        let mut buf = vec![0u8; buf_len];
        let encrypted = Aes256CbcEnc::new(encryption_key.into(), iv.as_ref().into())
            .encrypt_padded_b2b_mut::<Pkcs7>(data.as_ref(), &mut buf)?;

        let mac_key = &h[32..];
        let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(mac_key)?;
        mac.update(&iv);
        mac.update(&CURVE_TYPE.to_be_bytes());
        mac.update(&(x.len() as u16).to_be_bytes());
        mac.update(&x);
        mac.update(&(y.len() as u16).to_be_bytes());
        mac.update(&y);
        mac.update(&encrypted);
        let mac_bytes = mac.finalize().into_bytes();

        Ok(Self {
            iv,
            curve_type: CURVE_TYPE,
            x: x.as_ref().try_into().unwrap(),
            y: y.as_ref().try_into().unwrap(),
            encrypted: Vec::from(encrypted),
            mac: mac_bytes[..].try_into().unwrap(),
        })
    }

    /// Decrypts this encrypted object and returns the decrypted bytes.
    pub fn decrypt(&self, private_key: &PrivateKey) -> Result<Vec<u8>, DecryptError> {
        if self.curve_type != CURVE_TYPE {
            return Err(DecryptError::UnsupportedCurve(self.curve_type));
        }
        if self.x.len() != KEY_LEN || self.y.len() != KEY_LEN {
            return Err(DecryptError::InvalidKeyLength {
                x_len: self.x.len(),
                y_len: self.y.len(),
            });
        }
        let mut public_key_bytes = [0; 65];
        public_key_bytes[0] = 0x04;
        public_key_bytes[1..33].copy_from_slice(&self.x);
        public_key_bytes[33..].copy_from_slice(&self.y);
        let public_key = secp256k1::PublicKey::from_slice(&public_key_bytes)?;
        let secret_key = secp256k1::SecretKey::from_slice(private_key.as_ref())?;
        let shared_secret =
            secp256k1::ecdh::SharedSecret::new_with_hash(&public_key, &secret_key, |x, _y| {
                secp256k1::ecdh::SharedSecret::from_bytes(x)
            });

        let h = crate::hash::sha512(shared_secret);
        let mac_key = &h[32..];

        let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(mac_key)?;
        mac.update(&self.iv);
        mac.update(&self.curve_type.to_be_bytes());
        mac.update(&(self.x.len() as u16).to_be_bytes());
        mac.update(&self.x);
        mac.update(&(self.y.len() as u16).to_be_bytes());
        mac.update(&self.y);
        mac.update(&self.encrypted);
        mac.verify(&self.mac.into())?;

        let encryption_key = &h[..32];
        let mut buf = vec![0u8; self.encrypted.len()];
        let decrypted = Aes256CbcDec::new(encryption_key.into(), self.iv.as_ref().into())
            .decrypt_padded_b2b_mut::<Pkcs7>(&self.encrypted, &mut buf)?;
        Ok(Vec::from(decrypted))
    }
}

impl SizedReadFrom for Encrypted {
    fn sized_read_from(r: &mut dyn Read, len: usize) -> io::Result<Self>
    where
        Self: Sized,
    {
        let mut iv = [0; IV_LEN];
        r.read_exact(&mut iv)?;

        let curve_type = u16::read_from(r)?;

        let x_length = u16::read_from(r)?;

        let mut rt = r.take(x_length as u64);
        let mut x = Vec::with_capacity(x_length as usize);
        rt.read_to_end(&mut x)?;

        let y_length = u16::read_from(r)?;

        let mut rt = r.take(y_length as u64);
        let mut y = Vec::with_capacity(y_length as usize);
        rt.read_to_end(&mut y)?;

        let sub_len = IV_LEN
            + size_of::<u16>()
            + size_of::<u16>()
            + x_length as usize
            + size_of::<u16>()
            + y_length as usize
            + MAC_LEN;
        if sub_len > len {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                TooShortError::new(sub_len, len),
            ));
        }
        let encrypted_len = len - sub_len;
        let mut rt = r.take(encrypted_len as u64);
        let mut encrypted = Vec::with_capacity(encrypted_len);
        rt.read_to_end(&mut encrypted)?;

        let mut mac = [0; MAC_LEN];
        r.read_exact(&mut mac)?;

        Ok(Self {
            iv,
            curve_type,
            x,
            y,
            encrypted,
            mac,
        })
    }
}

impl WriteTo for Encrypted {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.iv.write_to(w)?;
        self.curve_type.write_to(w)?;
        (self.x.len() as u16).write_to(w)?;
        self.x.write_to(w)?;
        (self.y.len() as u16).write_to(w)?;
        self.y.write_to(w)?;
        self.encrypted.write_to(w)?;
        self.mac.write_to(w)?;
        Ok(())
    }
}

/// This error indicates
/// that the signing failed.
#[derive(Clone, Debug)]
pub enum SignError {
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
}

impl fmt::Display for SignError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secp256k1Error(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for SignError {}

impl From<secp256k1::Error> for SignError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

/// This error indicates
/// that the verification failed.
#[derive(Clone, Debug)]
pub enum VerifyError {
    /// An error was caught during a process using secp256k1.
    /// The actual error caught is returned as a payload of this variant.
    Secp256k1Error(secp256k1::Error),
}

impl fmt::Display for VerifyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Secp256k1Error(err) => err.fmt(f),
        }
    }
}

impl std::error::Error for VerifyError {}

impl From<secp256k1::Error> for VerifyError {
    fn from(err: secp256k1::Error) -> Self {
        Self::Secp256k1Error(err)
    }
}

/// A signature.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Signature {
    bytes: Vec<u8>,
}

fn sign_sha256(data: impl AsRef<[u8]>, private_key: &PrivateKey) -> Result<Signature, SignError> {
    let hash = sha256(data);
    let message = secp256k1::Message::from_digest_slice(hash.as_ref())?;
    let secret_key = secp256k1::SecretKey::from_slice(private_key.as_ref())?;
    let secp = secp256k1::Secp256k1::signing_only();
    let signature = secp.sign_ecdsa(&message, &secret_key);
    let bytes = Vec::from(signature.serialize_der().as_ref());
    Ok(Signature { bytes })
}

/// Signs on data using a private key.
pub fn sign(data: impl AsRef<[u8]>, private_key: &PrivateKey) -> Result<Signature, SignError> {
    sign_sha256(data, private_key)
}

/// Verifies a signature of data using a public key.
pub fn verify(
    data: impl AsRef<[u8]>,
    signature: &Signature,
    public_key: &PublicKey,
) -> Result<(), VerifyError> {
    let hash = sha256(data);
    let message = secp256k1::Message::from_digest_slice(hash.as_ref())?;
    let mut sig = secp256k1::ecdsa::Signature::from_der(&signature.bytes)?;
    sig.normalize_s();
    let mut public_key_bytes = [0; 65];
    public_key_bytes[0] = 0x04;
    public_key_bytes[1..33].copy_from_slice(&public_key.x);
    public_key_bytes[33..].copy_from_slice(&public_key.y);
    let pk = secp256k1::PublicKey::from_slice(&public_key_bytes)?;
    let secp = secp256k1::Secp256k1::verification_only();
    secp.verify_ecdsa(&message, &sig, &pk)?;
    Ok(())
}

impl WriteTo for Signature {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        let len: VarInt = self.bytes.len().into();
        len.write_to(w)?;
        self.bytes.write_to(w)?;
        Ok(())
    }
}

impl ReadFrom for Signature {
    fn read_from(r: &mut dyn Read) -> io::Result<Self>
    where
        Self: Sized,
    {
        let len = VarInt::read_from(r)?;
        if len.as_u64() > message::Object::MAX_OBJECT_PAYLOAD_LENGTH as u64 {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                TooLongError::new(
                    message::Object::MAX_OBJECT_PAYLOAD_LENGTH,
                    len.as_u64() as usize,
                ),
            ));
        }
        let bytes = Vec::<u8>::sized_read_from(r, len.as_u64() as usize)?;
        Ok(Self { bytes })
    }
}

impl LenBm for Signature {
    fn len_bm(&self) -> usize {
        let len: VarInt = self.bytes.len().into();
        len.len_bm() + self.bytes.len()
    }
}