Skip to content

Commit

Permalink
fix(wasm): compilable and updated some bindings
Browse files Browse the repository at this point in the history
Signed-off-by: blu3beri <blu3beri@proton.me>
  • Loading branch information
blu3beri authored and appetrosyan committed Mar 19, 2023
1 parent 87009a0 commit 390f004
Show file tree
Hide file tree
Showing 14 changed files with 419 additions and 186 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
cargo-registry
target
pkg
build
.idea
*.iml
Expand Down
111 changes: 111 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion libursa/.gitignore

This file was deleted.

3 changes: 3 additions & 0 deletions libursa/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion libursa/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ sharing_native = ["failure", "int_traits", "lazy_static", "log", "openssl", "ran
signatures = ["cl", "ed25519", "ecdsa_secp256k1", "bls_bls12381", "bls_bn254"]
signatures_native = ["cl_native", "ed25519", "ecdsa_secp256k1_native", "bls_bls12381", "bls_bn254"]
signatures_asm = ["cl_native", "ed25519_asm", "ecdsa_secp256k1_asm", "bls_bls12381", "bls_bn254_asm"]
wasm = ["console_error_panic_hook", "failure", "hex", "js-sys", "log", "rand/wasm-bindgen", "serde", "serde_json", "wasm-bindgen", "zeroize"]
wasm = ["console_error_panic_hook", "failure", "hex", "js-sys", "log", "rand/wasm-bindgen", "serde", "serde_json", "wasm-bindgen", "zeroize", "getrandom"]
x25519 = ["arrayref", "curve25519-dalek/std", "curve25519-dalek/u64_backend", "hex", "rand", "rand_chacha", "sha2/std", "x25519-dalek/std", "x25519-dalek/u64_backend", "zeroize"]
x25519_asm = ["arrayref", "curve25519-dalek/nightly", "curve25519-dalek/avx2_backend", "hex", "rand", "rand_chacha", "sha2/asm", "x25519-dalek/nightly", "x25519-dalek/u64_backend", "zeroize"]

Expand Down Expand Up @@ -137,6 +137,7 @@ num-traits = { version = "=0.2.11", optional = true }
openssl = { version = "0.10", optional = true }
# TODO: Find out if the wasm-bindgen feature can be made dependent on our own wasm feature
rand = { version = "0.7", features = ["wasm-bindgen"], optional = true }
getrandom = { version = "0.2", features = ["js"], optional = true }
rand_chacha = { version = "=0.2.1", optional = true }
rustchacha20poly1305 = { version = "0.7", package = "chacha20poly1305", optional = true }
k256 = { version = "0.9.6", optional = true, features = ["ecdh", "ecdsa", "sha256"]}
Expand Down
12 changes: 7 additions & 5 deletions libursa/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,14 @@ pub mod utils;

#[cfg(any(feature = "bls_bn254", feature = "bls_bn254_asm"))]
pub mod bls;
#[cfg(any(feature = "cl_native", feature = "sharing_native"))]
#[path = "bn/openssl.rs"]
pub mod bn;
#[cfg(any(feature = "cl", feature = "sharing"))]
#[path = "bn/rust.rs"]

#[cfg_attr(
any(feature = "cl_native", feature = "sharing_native"),
path = "bn/openssl.rs"
)]
#[cfg_attr(any(feature = "cl", feature = "sharing"), path = "bn/rust.rs")]
pub mod bn;

#[cfg(any(feature = "cl", feature = "cl_native"))]
pub mod cl;
#[cfg(any(
Expand Down
89 changes: 60 additions & 29 deletions libursa/src/signatures/secp256k1.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use super::*;

use sha2::digest::generic_array::typenum::U32;
use CryptoError;

use rand::rngs::OsRng;

#[cfg(feature = "serde")]
use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};

Expand Down Expand Up @@ -116,6 +115,7 @@ mod ecdsa_secp256k1 {
use sha2::Digest;
use zeroize::Zeroize;

use rand::rngs::OsRng;
use rand::{RngCore, SeedableRng};
use rand_chacha::ChaChaRng;

Expand Down Expand Up @@ -217,74 +217,105 @@ mod ecdsa_secp256k1 {
#[cfg(feature = "ecdsa_secp256k1")]
mod ecdsa_secp256k1 {
use super::*;
use k256;

use rand::{RngCore, SeedableRng};
use rand_chacha::ChaChaRng;
use zeroize::Zeroize;

use amcl::secp256k1::{ecdh, ecp};
use amcl_wrapper::amcl::secp256k1::ecp::ECP;
use k256::ecdsa::signature::{Signature, Signer, Verifier};
use k256::elliptic_curve::rand_core::OsRng;
use k256::EncodedPoint;
use sha2::Digest;

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct EcdsaSecp256k1Impl;

impl EcdsaSecp256k1Impl {
pub fn public_key_compressed(&self, pk: &PublicKey) -> Vec<u8> {
let mut compressed = [0u8; PUBLIC_KEY_SIZE];
ecp::ECP::frombytes(&pk[..]).tobytes(&mut compressed, true);
ECP::frombytes(&pk[..]).tobytes(&mut compressed, true);
compressed.to_vec()
}

pub fn public_key_uncompressed(&self, pk: &PublicKey) -> Vec<u8> {
let mut uncompressed = [0u8; PUBLIC_UNCOMPRESSED_KEY_SIZE];
ecp::ECP::frombytes(&pk[..]).tobytes(&mut uncompressed, false);
ECP::frombytes(&pk[..]).tobytes(&mut uncompressed, false);
uncompressed.to_vec()
}

pub fn parse(&self, data: &[u8]) -> Result<PublicKey, CryptoError> {
match data.len() {
PUBLIC_KEY_SIZE => Ok(PublicKey(data.to_vec())),
PUBLIC_UNCOMPRESSED_KEY_SIZE => {
let mut compressed = [0u8; PUBLIC_KEY_SIZE];
ecp::ECP::frombytes(data).tobytes(&mut compressed, true);
ECP::frombytes(data).tobytes(&mut compressed, true);
Ok(PublicKey(compressed.to_vec()))
}
_ => Err(CryptoError::ParseError("Invalid key length".to_string())),
}
}

pub fn new() -> Self {
Self {}
}
pub fn keypair(

pub fn keypair<D>(
&self,
option: Option<KeyGenOption>,
) -> Result<(PublicKey, PrivateKey), CryptoError> {
let signing_key = k256::SigningKey::random(&mut OsRng);
let sk = signing_key::to_bytes();
let verify_key = signing_key.verify_key();
let compressed = verify_key::to_bytes(); //serialized as compressed point
) -> Result<(PublicKey, PrivateKey), CryptoError>
where
D: Digest<OutputSize = U32>,
{
let signing_key = match option {
Some(ref o) => match o {
KeyGenOption::FromSecretKey(s) => k256::ecdsa::SigningKey::from_bytes(&s.0),
_ => unreachable!(),
},
None => Ok(k256::ecdsa::SigningKey::random(&mut OsRng)),
}
.map_err(|e| CryptoError::KeyGenError(format!("{:?}", e)))?;
let sk = signing_key.to_bytes();
let verify_key = signing_key.verifying_key();
let compressed = verify_key.to_bytes(); //serialized as compressed point
Ok((PublicKey(compressed.to_vec()), PrivateKey(sk.to_vec())))
}
pub fn sign(&self, message: &[u8], sk: &PrivateKey) -> Result<Vec<u8>, CryptoError> {
let signing_key = k256::SigningKey::new(&sk)

pub fn sign<D>(&self, message: &[u8], sk: &PrivateKey) -> Result<Vec<u8>, CryptoError>
where
D: Digest<OutputSize = U32>,
{
let signing_key = k256::ecdsa::SigningKey::from_bytes(&sk.0)
.map_err(|e| CryptoError::SigningError(format!("{:?}", e)))?;
let (sig, _) = k256::signing_key.sign(&message);
Ok(sig.serialize().to_vec())
let sig: k256::ecdsa::Signature = signing_key.sign(message);
Ok(k256::ecdsa::signature::Signature::as_bytes(&sig).to_vec())
}
pub fn verify(

pub fn verify<D>(
&self,
message: &[u8],
signature: &[u8],
pk: &PublicKey,
) -> Result<bool, CryptoError> {
) -> Result<bool, CryptoError>
where
D: Digest<OutputSize = U32>,
{
let digest = D::digest(message);
let message = digest.as_slice();
let compressed_pk = self.public_key_compressed(pk);
let pk = k256::VerifyKey::from_encoded_point(compressed_pk)
let encoded_point = EncodedPoint::from_bytes(compressed_pk)
.map_err(|e| CryptoError::SigningError(format!("{:?}", e)))?;
let pk = k256::ecdsa::VerifyingKey::from_encoded_point(&encoded_point)
.map_err(|e| CryptoError::SigningError(format!("{:?}", e)))?;
let sig: Signature = k256::Signature::from_bytes(signature);
Ok(k256::verify(&msg, &sig, &pk))
let sig = <k256::ecdsa::Signature as k256::ecdsa::signature::Signature>::from_bytes(
signature,
)
.map_err(|e| CryptoError::SigningError(format!("{:?}", e)))?;
Ok(pk.verify(&message, &sig).is_ok())
}

pub fn normalize_s(&self, signature: &mut [u8]) -> Result<(), CryptoError> {
let mut sig = k256::Signature::parse(array_ref!(signature, 0, SIGNATURE_SIZE));
sig.normalize_s();
array_copy!(sig.serialize(), signature, 0, SIGNATURE_SIZE);
let mut sig = k256::ecdsa::Signature::from_bytes(signature)
.map_err(|e| CryptoError::ParseError(format!("{:?}", e)))?;
sig.normalize_s()
.map_err(|e| CryptoError::ParseError(format!("{:?}", e)))?;
array_copy!(sig.as_bytes(), signature, 0, SIGNATURE_SIZE);
Ok(())
}
}
Expand Down
Loading

0 comments on commit 390f004

Please sign in to comment.