laron-crypto 0.2.3

Cryptography helper library
Documentation
// This file is part of the laron-crypto
//
// Copyright 2023 Ade M Ramdani
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::error::{Error, Result};
use constant_time_eq::constant_time_eq;
use k256::elliptic_curve::group::prime::PrimeCurveAffine;
use k256::elliptic_curve::sec1::ToEncodedPoint;
use k256::{AffinePoint, NonZeroScalar};

/// Byte size of the public key
const SIZE: usize = 65;

/// Public key
#[derive(Debug, Clone, Copy)]
pub struct PublicKey {
    bytes: [u8; SIZE],
}

impl PartialEq for PublicKey {
    fn eq(&self, other: &Self) -> bool {
        constant_time_eq(&self.bytes, &other.bytes)
    }
}

impl Eq for PublicKey {}

impl PublicKey {
    /// Create public key from bytes
    pub fn from_bytes(bytes: [u8; SIZE]) -> Self {
        Self { bytes }
    }

    /// Create public key from slice
    pub fn from_slice(slice: &[u8]) -> Result<Self> {
        if slice.len() != SIZE {
            Err(Error::LengthError(format!(
                "PublicKey size must be {} bytes got {} bytes.",
                SIZE,
                slice.len()
            )))
        } else {
            let mut new_bytes = [0u8; SIZE];
            new_bytes.copy_from_slice(slice);
            Ok(Self::from_bytes(new_bytes))
        }
    }

    /// Create public key from hex string
    pub fn from_hex(hex: &str) -> Result<Self> {
        if hex.len() != SIZE * 2 {
            Err(Error::LengthError(format!(
                "PublicKey hex must be {} characters got {} characters.",
                SIZE * 2,
                hex.len()
            )))
        } else {
            let bytes = hex::decode(hex)?;
            Self::from_slice(&bytes)
        }
    }

    /// Get public key as bytes
    pub fn as_bytes(&self) -> [u8; SIZE] {
        self.bytes
    }

    /// Get public key as compressed bytes
    pub fn as_compressed_bytes(&self) -> [u8; 33] {
        let pk = k256::PublicKey::from_sec1_bytes(&self.bytes).unwrap();
        let bytes = pk.to_encoded_point(true);
        bytes.as_bytes().try_into().unwrap()
    }

    /// Get public key as slice
    pub fn as_slice(&self) -> &[u8] {
        &self.bytes
    }

    /// Get public key as hex string
    pub fn as_hex(&self) -> String {
        hex::encode(&self.bytes)
    }

    /// Derive child key from parent key.
    pub fn derive_child(&self, other: [u8; 32]) -> Result<Self> {
        let current = k256::PublicKey::from_sec1_bytes(&self.bytes).unwrap();
        let child_scalar = Option::<NonZeroScalar>::from(NonZeroScalar::from_repr(other.into()))
            .ok_or(Error::InvalidPublicKey)?;
        let child_point = current.to_projective() + (AffinePoint::generator() * *child_scalar);
        let derived = k256::PublicKey::from_affine(child_point.into())
            .map_err(|_| Error::InvalidPublicKey)?;
        let bytes = derived.to_encoded_point(false);
        Self::from_slice(bytes.as_bytes())
    }
}

#[cfg(test)]
mod tests {
    use crate::PrivateKey;

    use super::*;

    #[test]
    fn test_public_key() {
        let key = PrivateKey::new();
        let pk = key.public_key();
        let pk_bytes = pk.as_bytes();
        let pk_hex = pk.as_hex();
        let pk_slice = pk.as_slice();
        let pk_compressed = pk.as_compressed_bytes();
        assert_eq!(pk_bytes.len(), SIZE);
        assert_eq!(pk_hex.len(), SIZE * 2);
        assert_eq!(pk_slice.len(), SIZE);
        assert_eq!(pk_compressed.len(), 33);
        assert_eq!(pk, PublicKey::from_slice(pk_slice).unwrap());
        assert_eq!(pk, PublicKey::from_hex(&pk_hex).unwrap());
    }
}