add sample

This commit is contained in:
mii8080
2022-05-31 03:20:54 +00:00
committed by GitHub
parent 790209c646
commit ee9900601a
3 changed files with 33 additions and 9 deletions

View File

@ -1,4 +1,4 @@
use std::ops::{Add, Mul, Neg};
use std::{ops::{Add, Mul, Neg}, fmt::Display};
use primitive_types::U512;
@ -27,6 +27,16 @@ pub enum EllipticCurvePoint {
Infinity
}
impl Display for EllipticCurvePoint {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let EllipticCurvePoint::Point { x, y, a, b } = self {
write!(f, "({:x}, {:x})", x.value, y.value)
} else {
write!(f, "Infinity")
}
}
}
impl EllipticCurvePoint {
pub fn check(self) -> bool {
match self {

View File

@ -1,4 +1,4 @@
use std::ops::Add;
use std::ops::{Add, Sub};
use primitive_types::{U512, U256};
@ -7,7 +7,7 @@ use rand_chacha::{ChaCha20Rng, rand_core::{SeedableRng, RngCore}};
use super::elliptic_curve::{EllipticCurve, EllipticCurvePoint};
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Encryption {
pub ellictic_curve: EllipticCurve,
pub base_point: EllipticCurvePoint,
@ -15,7 +15,7 @@ pub struct Encryption {
pub plain_mapping: Vec<EllipticCurvePoint>
}
#[derive(Debug)]
#[derive(Debug, Clone, Copy)]
pub struct EncryptedEllipticCurvePoint {
pub data: EllipticCurvePoint,
pub rp: EllipticCurvePoint
@ -32,6 +32,17 @@ impl Add for EncryptedEllipticCurvePoint {
}
}
impl Sub for EncryptedEllipticCurvePoint {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Self {
data: self.data + (-rhs.data),
rp: self.rp + (-rhs.rp)
}
}
}
impl Encryption {
pub fn ec_point_to_plain(&self, point: EllipticCurvePoint) -> U512 {
match point {

View File

@ -37,17 +37,20 @@ fn main() {
};
let private_key = Encryption::get_private_key();
println!("private_key: {:?}", private_key);
println!("private_key: {:x}", private_key);
let public_key = encryption.get_public_key(private_key);
println!("public_key: {:?}", public_key);
println!("public_key: {}", public_key);
let ten = encryption.plain_to_ec_point(U512::from(13u32));
let ten = encryption.plain_to_ec_point(U512::from(10u32));
let e_ten = encryption.encrypt(ten, public_key, None);
println!("10 -> {}", e_ten.data);
let two = encryption.plain_to_ec_point(U512::from(27000u32));
let two = encryption.plain_to_ec_point(U512::from(2u32));
let e_two = encryption.encrypt(two, public_key, None);
println!("2 -> {}", e_two.data);
println!("{:?}", encryption.ec_point_to_plain(Encryption::decrypt(e_ten + e_two, private_key)));
println!("10 + 2 -> {}", (e_ten + e_two).data);
println!("decrypt: {:?}", encryption.ec_point_to_plain(Encryption::decrypt(e_ten + e_two, private_key)));
/*
let twenty = encryption.plain_to_ec_point(U512::from(12u8));