use alloc::vec::Vec;
use crate::{
bytes::{BigEndianBytes, PlaintextBytes},
error::Result,
material::{CiphertextBytes, SharedSecretBytes, SignatureBytes},
rng::CryptoRng,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EccCurve {
P192,
P224,
P256,
P384,
P521,
Sm2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RsaPadding {
Pkcs1v15,
Pss,
Oaep,
None,
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct RsaPublicComponents {
n: BigEndianBytes,
e: BigEndianBytes,
}
impl RsaPublicComponents {
pub fn new(n: BigEndianBytes, e: BigEndianBytes) -> Self {
Self { n, e }
}
pub fn from_be_bytes(n: Vec<u8>, e: Vec<u8>) -> Self {
Self::new(BigEndianBytes::new(n), BigEndianBytes::new(e))
}
pub fn n(&self) -> &[u8] {
self.n.as_bytes()
}
pub fn e(&self) -> &[u8] {
self.e.as_bytes()
}
pub fn into_parts(self) -> (BigEndianBytes, BigEndianBytes) {
(self.n, self.e)
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct EccPublicPoint {
curve: EccCurve,
x: BigEndianBytes,
y: BigEndianBytes,
}
impl EccPublicPoint {
pub fn new(curve: EccCurve, x: BigEndianBytes, y: BigEndianBytes) -> Self {
Self { curve, x, y }
}
pub fn from_be_bytes(curve: EccCurve, x: Vec<u8>, y: Vec<u8>) -> Self {
Self::new(curve, BigEndianBytes::new(x), BigEndianBytes::new(y))
}
pub fn curve(&self) -> EccCurve {
self.curve
}
pub fn x(&self) -> &[u8] {
self.x.as_bytes()
}
pub fn y(&self) -> &[u8] {
self.y.as_bytes()
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Sm2PublicPoint {
x: BigEndianBytes,
y: BigEndianBytes,
}
impl Sm2PublicPoint {
pub fn new(x: BigEndianBytes, y: BigEndianBytes) -> Self {
Self { x, y }
}
pub fn from_be_bytes(x: Vec<u8>, y: Vec<u8>) -> Self {
Self::new(BigEndianBytes::new(x), BigEndianBytes::new(y))
}
pub fn x(&self) -> &[u8] {
self.x.as_bytes()
}
pub fn y(&self) -> &[u8] {
self.y.as_bytes()
}
}
#[derive(Debug, Clone)]
pub enum PublicKeyComponents {
Rsa(RsaPublicComponents),
Ecc(EccPublicPoint),
Sm2(Sm2PublicPoint),
}
pub trait Keypair {
fn generate(rng: &mut dyn CryptoRng, key_size_bits: usize) -> Result<Self>
where
Self: Sized;
fn to_public_components(&self) -> Result<PublicKeyComponents>;
}
pub trait Signer {
fn sign(&self, msg: &[u8], rng: &mut dyn CryptoRng) -> Result<SignatureBytes>;
}
pub trait Verifier {
fn verify(&self, msg: &[u8], signature: &SignatureBytes) -> Result<()>;
}
pub trait Encryptor {
fn encrypt(&self, msg: &[u8], rng: &mut dyn CryptoRng) -> Result<CiphertextBytes>;
}
pub trait Decryptor {
fn decrypt(&self, ciphertext: &CiphertextBytes) -> Result<PlaintextBytes>;
}
pub trait KeyAgreement {
fn shared_secret(&self, peer_public: &PublicKeyComponents) -> Result<SharedSecretBytes>;
}