Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use zkryptium for cryptographic operations inside Memstore #1351

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ serde = { version = "1.0", default-features = false, features = ["alloc", "deriv
thiserror = { version = "1.0", default-features = false }
strum = { version = "0.25", default-features = false, features = ["std", "derive"] }
serde_json = { version = "1.0", default-features = false }
json-proof-token = { version = "0.3.4" }
zkryptium = { version = "0.2.0", default-features = false, features = ["bbsplus"] }
json-proof-token = { version = "0.3.5" }
zkryptium = { version = "0.2.1", default-features = false, features = ["bbsplus"] }

[workspace.package]
authors = ["IOTA Stiftung"]
Expand Down
2 changes: 1 addition & 1 deletion examples/1_advanced/10_zkp_revocation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ async fn main() -> anyhow::Result<()> {
&client,
&secret_manager_issuer,
&storage_issuer,
JwkMemStore::BLS12381SHA256_KEY_TYPE,
JwkMemStore::BLS12381G2_KEY_TYPE,
None,
Some(ProofAlgorithm::BLS12381_SHA256),
)
Expand Down
2 changes: 1 addition & 1 deletion examples/1_advanced/9_zkp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async fn main() -> anyhow::Result<()> {
&client,
&secret_manager_issuer,
&storage_issuer,
JwkMemStore::BLS12381SHA256_KEY_TYPE,
JwkMemStore::BLS12381G2_KEY_TYPE,
ProofAlgorithm::BLS12381_SHA256,
)
.await?;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ impl SelectiveDisclosurePresentation {

/// Set Presentation Protected Header.
pub fn set_presentation_header(&mut self, ph: PresentationProtectedHeader) {
self.jwp_builder.presentation_protected_header(ph);
self.jwp_builder.set_presentation_protected_header(ph);
}

/// Get the builder.
Expand Down
14 changes: 9 additions & 5 deletions identity_jose/src/jwk/curve/bls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ use core::fmt::Result;
/// [More Info](https://datatracker.ietf.org/doc/html/draft-ietf-cose-bls-key-representations-05#name-curve-parameter-registratio)
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum BlsCurve {
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 12 with 381-bit p in the subgroup of G1.
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 12 with 381-bit p in the
/// subgroup of G1.
BLS12381G1,
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 12 with 381-bit p in the subgroup of G2.
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 12 with 381-bit p in the
/// subgroup of G2.
BLS12381G2,
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 48 with 581-bit p in the subgroup of G1.
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 48 with 581-bit p in the
/// subgroup of G1.
BLS48581G1,
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 48 with 581-bit p in the subgroup of G2.
/// A cryptographic key on the Barreto-Lynn-Scott (BLS) curve featuring an embedding degree 48 with 581-bit p in the
/// subgroup of G2.
BLS48581G2,
}

Expand All @@ -33,4 +37,4 @@ impl Display for BlsCurve {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
f.write_str(self.name())
}
}
}
4 changes: 2 additions & 2 deletions identity_jose/src/jwk/curve/mod.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// Copyright 2020-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

mod bls;
mod ec;
mod ecx;
mod ed;
mod bls;

pub use self::bls::*;
pub use self::ec::*;
pub use self::ecx::*;
pub use self::ed::*;
pub use self::bls::*;
4 changes: 2 additions & 2 deletions identity_jose/src/jwk/jwk_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl TryFrom<JwkExt> for Jwk {

let (kty, params) = match value.key_params {
JwkAlgorithmParameters::EllipticCurve(p) => (JwkType::Ec, JwkParams::Ec(JwkParamsEc::from(p))),
_ => unreachable!()
_ => unreachable!(),
};

Ok(Self {
Expand Down Expand Up @@ -156,4 +156,4 @@ impl TryInto<JwkExt> for &Jwk {
key_params: params,
})
}
}
}
13 changes: 13 additions & 0 deletions identity_jose/src/jwk/key_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ use crate::jwk::EcxCurve;
use crate::jwk::EdCurve;
use crate::jwk::JwkType;

use super::BlsCurve;

/// Algorithm-specific parameters for JSON Web Keys.
///
/// [More Info](https://tools.ietf.org/html/rfc7518#section-6)
Expand Down Expand Up @@ -149,6 +151,17 @@ impl JwkParamsEc {
_ => Err(Error::KeyError("Ec Curve")),
}
}

/// Returns the [`BlsCurve`] if it is of a supported type.
pub fn try_bls_curve(&self) -> Result<BlsCurve> {
match &*self.crv {
"BLS12381G1" => Ok(BlsCurve::BLS12381G1),
"BLS12381G2" => Ok(BlsCurve::BLS12381G2),
"BLS48581G1" => Ok(BlsCurve::BLS48581G1),
"BLS48581G2" => Ok(BlsCurve::BLS48581G2),
_ => Err(Error::KeyError("BLS Curve")),
}
}
}

impl From<JwkParamsEc> for JwkParams {
Expand Down
87 changes: 87 additions & 0 deletions identity_storage/src/key_storage/bls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
use identity_verification::jose::jwk::Jwk;
use identity_verification::jose::jwu;
use identity_verification::jwk::BlsCurve;
use identity_verification::jwk::JwkParamsEc;
use zkryptium::bbsplus::keys::BBSplusPublicKey;
use zkryptium::bbsplus::keys::BBSplusSecretKey;

use crate::key_storage::KeyStorageError;
use crate::key_storage::KeyStorageErrorKind;
use crate::key_storage::KeyStorageResult;

pub(crate) fn expand_bls_jwk(jwk: &Jwk) -> KeyStorageResult<(BBSplusSecretKey, BBSplusPublicKey)> {
let params: &JwkParamsEc = jwk.try_ec_params().unwrap();

if params
.try_bls_curve()
.map_err(|err| KeyStorageError::new(KeyStorageErrorKind::UnsupportedKeyType).with_source(err))?
!= BlsCurve::BLS12381G2
{
return Err(
KeyStorageError::new(KeyStorageErrorKind::UnsupportedKeyType)
.with_custom_message(format!("expected an {} key", BlsCurve::BLS12381G2.name())),
);
}

let sk: BBSplusSecretKey = params
.d
.as_deref()
.map(jwu::decode_b64)
.ok_or_else(|| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_custom_message("expected Jwk `d` param to be present")
})?
.map(|v| BBSplusSecretKey::from_bytes(&v))
.map_err(|err| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified)
.with_custom_message("unable to decode `d` param")
.with_source(err)
})?
.map_err(|_| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_custom_message(format!("invalid BBS+ secret key"))
})?;

let x: [u8; BBSplusPublicKey::COORDINATE_LEN] = jwu::decode_b64(&params.x)
.map_err(|err| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified)
.with_custom_message("unable to decode `x` param")
.with_source(err)
})?
.try_into()
.map_err(|_| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified)
.with_custom_message(format!("expected key of length {}", BBSplusPublicKey::COORDINATE_LEN))
})?;

let y: [u8; BBSplusPublicKey::COORDINATE_LEN] = jwu::decode_b64(&params.y)
.map_err(|err| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified)
.with_custom_message("unable to decode `y` param")
.with_source(err)
})?
.try_into()
.map_err(|_| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified)
.with_custom_message(format!("expected key of length {}", BBSplusPublicKey::COORDINATE_LEN))
})?;

let pk = BBSplusPublicKey::from_coordinates(&x, &y).map_err(|_| {
KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_custom_message(format!("invalid BBS+ public key"))
})?;

Ok((sk, pk))
}

#[cfg(any(test, feature = "memstore"))]
pub(crate) fn encode_bls_jwk(private_key: &BBSplusSecretKey, public_key: &BBSplusPublicKey) -> Jwk {
let (x, y) = public_key.to_coordinates();
let x = jwu::encode_b64(x);
let y = jwu::encode_b64(y);

let d = jwu::encode_b64(private_key.to_bytes());
let mut params = JwkParamsEc::new();
params.x = x;
params.y = y;
params.d = Some(d);
params.crv = BlsCurve::BLS12381G2.name().to_owned();
Jwk::from_params(params)
}
19 changes: 9 additions & 10 deletions identity_storage/src/key_storage/jwk_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ use async_trait::async_trait;
use identity_verification::jose::jwk::Jwk;
use identity_verification::jose::jws::JwsAlgorithm;
use jsonprooftoken::jpa::algs::ProofAlgorithm;
use jsonprooftoken::jpt::claims::JptClaims;
use jsonprooftoken::jwp::header::IssuerProtectedHeader;
use zkryptium::bbsplus::signature::BBSplusSignature;

use super::jwk_gen_output::JwkGenOutput;
Expand Down Expand Up @@ -73,23 +71,24 @@ pub trait JwkStorage: storage_sub_trait::StorageSendSyncMaybe {
#[cfg_attr(feature = "send-sync-storage", async_trait)]
pub trait JwkStorageExt: JwkStorage {
/// Generates a JWK representing a BBS+ signature
async fn generate_bbs_key(&self, key_type: KeyType, alg: ProofAlgorithm) -> KeyStorageResult<JwkGenOutput>;
async fn generate_bbs(&self, key_type: KeyType, alg: ProofAlgorithm) -> KeyStorageResult<JwkGenOutput>;

/// Generate the JPT representing a JWP in the Issuer form
async fn generate_issuer_proof(
/// Sign the provided `data` and `header` using the private key identified by `key_id` according to the requirements
/// of the corresponding `public_key` (see [`Jwk::alg`](Jwk::alg()) etc.).
async fn sign_bbs(
&self,
key_id: &KeyId,
header: IssuerProtectedHeader,
claims: JptClaims,
data: &[Vec<u8>],
header: &[u8],
public_key: &Jwk,
) -> KeyStorageResult<String>;
) -> KeyStorageResult<Vec<u8>>;

/// Update proof functionality for timeframe revocation mechanism
async fn update_proof(
async fn update_signature(
&self,
key_id: &KeyId,
public_key: &Jwk,
proof: &[u8; BBSplusSignature::BYTES],
signature: &[u8; BBSplusSignature::BYTES],
ctx: ProofUpdateCtx,
) -> KeyStorageResult<[u8; BBSplusSignature::BYTES]>;
}
Loading
Loading