Skip to content

Commit

Permalink
be able to use BLS keys as ECIES keys
Browse files Browse the repository at this point in the history
  • Loading branch information
benr-ml committed Oct 2, 2023
1 parent 6315731 commit 5b44157
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
10 changes: 10 additions & 0 deletions fastcrypto-tbls/src/ecies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ where
Self(G::ScalarType::rand(rng))
}

pub fn from(sc: G::ScalarType) -> Self {
Self(sc)
}

pub fn decrypt(&self, enc: &Encryption<G>) -> Vec<u8> {
enc.decrypt(&self.0)
}
Expand Down Expand Up @@ -112,6 +116,12 @@ where
}
}

impl<G: GroupElement> From<G> for PublicKey<G> {
fn from(p: G) -> Self {
Self(p)
}
}

impl<G: GroupElement + Serialize> Encryption<G> {
fn deterministic_encrypt(msg: &[u8], r_g: &G, r_x_g: &G) -> Self {
let hkdf_result = Self::hkdf(r_x_g);
Expand Down
19 changes: 19 additions & 0 deletions fastcrypto-tbls/src/tests/ecies_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

use crate::ecies::*;
use crate::random_oracle::RandomOracle;
use fastcrypto::bls12381::min_sig::BLS12381KeyPair;
use fastcrypto::groups::bls12381::{G2Element, Scalar};
use fastcrypto::groups::ristretto255::RistrettoPoint;
use fastcrypto::groups::GroupElement;
use fastcrypto::traits::KeyPair;
use rand::thread_rng;

const MSG: &[u8; 4] = b"test";
Expand Down Expand Up @@ -42,3 +46,18 @@ fn test_recovery_package() {
.decrypt_with_recovery_package(&pkg, &ro, &encryption)
.is_err());
}

#[test]
fn test_blskeypair_to_group() {
let pair = BLS12381KeyPair::generate(&mut thread_rng());
let (pk, sk) = (pair.public().clone(), pair.private());
let pk: G2Element = bcs::from_bytes(pk.as_ref()).expect("should work");
let ecies_pk = PublicKey::<G2Element>::from(pk);
let sk: Scalar = bcs::from_bytes(sk.as_ref()).expect("should work");
let ecies_sk = PrivateKey::<G2Element>::from(sk);
assert_eq!(
ecies_pk,
PublicKey::<G2Element>::from_private_key(&ecies_sk)
);
assert_eq!(*ecies_pk.as_element(), G2Element::generator() * sk);
}
2 changes: 1 addition & 1 deletion fastcrypto/src/groups/bls12381.rs
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ impl ScalarType for Scalar {
impl FiatShamirChallenge for Scalar {
fn fiat_shamir_reduction_to_group_element(uniform_buffer: &[u8]) -> Self {
const INPUT_LENGTH: usize = SCALAR_LENGTH - 10; // Safe for our prime field
assert!(INPUT_LENGTH >= uniform_buffer.len());
assert!(INPUT_LENGTH <= uniform_buffer.len());
let mut bytes = [0u8; INPUT_LENGTH];
bytes.copy_from_slice(&uniform_buffer[..INPUT_LENGTH]);
let mut ret = blst_fr::default();
Expand Down

0 comments on commit 5b44157

Please sign in to comment.