core_crypto/keypair_schema.rs
1// Copyright 2021 BlockPuppets developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! A Rust implementation of Nis1 and Symbol ed25519 keypair generation, signing, and verification.
10//!
11//! This is the reference documentation for the proptest API.
12//!
13//! For documentation on how to get started with Nis1 keypair and general usage
14//! advice, please refer to the [Key pair](https://docs.nem.io/en/nem-sdk/private-key#6-2-create-key-pairs).
15//!
16//! For documentation on how to get started with Symbol keypair and general usage
17//! advice, please refer to the [Key pair](https://docs.symbolplatform.com/concepts/cryptography.html#keypair).
18//!
19
20use std::fmt::Debug;
21
22use anyhow::Result;
23
24use super::{BlockCipher, PrivateKey, PublicKey, Signature, KEYPAIR_LENGTH, KEY_BYTES_SIZE};
25
26/// This trait defines a schema: an association of symbol or nis1 keypair type.
27///
28pub trait KeyPairSchema: Sized + PartialEq + Debug + Copy {
29 type Crypto: BlockCipher;
30
31 /// Create a new `Keypair` with cryptographically random content.
32 ///
33 fn random() -> Self;
34
35 /// Construct a `Keypair` from the bytes of a `PublicKey` and `PrivateKey`.
36 ///
37 fn from_bytes(bytes: &[u8]) -> Result<Self>;
38
39 /// Construct a `Keypair` from a hex encoded private key string.
40 ///
41 fn from_hex_private_key<S: AsRef<str>>(hex: S) -> Result<Self>;
42
43 /// Construct a `Keypair` `PrivateKey` type.
44 ///
45 fn from_private_key(pk: PrivateKey) -> Self;
46
47 fn private_key(&self) -> PrivateKey;
48
49 fn public_key(&self) -> PublicKey;
50
51 /// Signs a data bytes with a `Keypair`.
52 ///
53 fn sign(&self, data: &[u8]) -> Signature;
54
55 /// Verify a `Signature` on a data with this Keypair public key.
56 ///
57 fn verify(&self, data: &[u8], signature: Signature) -> Result<()>;
58
59 fn from_null_private_key(pk: PublicKey) -> Self;
60
61 /// Convert this keypair to bytes.
62 ///
63 /// # Returns
64 ///
65 /// An array of bytes, `[u8; KEYPAIR_LENGTH]`. The first
66 /// `KEY_BYTES_SIZE` of bytes is the `PrivateKey`, and the next
67 /// `KEY_BYTES_SIZE` bytes is the `PublicKey`.
68 fn to_bytes(&self) -> [u8; KEYPAIR_LENGTH] {
69 let mut bytes: [u8; KEYPAIR_LENGTH] = [0u8; KEYPAIR_LENGTH];
70
71 bytes[..KEY_BYTES_SIZE].copy_from_slice(self.private_key().as_bytes());
72 bytes[KEY_BYTES_SIZE..].copy_from_slice(self.public_key().as_bytes());
73 bytes
74 }
75}