identity_storage/key_storage/
bls.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright 2020-2024 IOTA Stiftung, Fondazione Links
// SPDX-License-Identifier: Apache-2.0

use anyhow::Context;
use identity_verification::jose::jwk::Jwk;
use identity_verification::jose::jwu;
use identity_verification::jwk::BlsCurve;
use identity_verification::jwk::JwkParamsEc;
use jsonprooftoken::jpa::algs::ProofAlgorithm;
use zkryptium::bbsplus::ciphersuites::BbsCiphersuite;
use zkryptium::bbsplus::ciphersuites::Bls12381Sha256;
use zkryptium::bbsplus::ciphersuites::Bls12381Shake256;
use zkryptium::bbsplus::keys::BBSplusPublicKey;
use zkryptium::bbsplus::keys::BBSplusSecretKey;
use zkryptium::keys::pair::KeyPair;
use zkryptium::schemes::algorithms::BBSplus;
use zkryptium::schemes::generics::Signature;

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

fn random_bbs_keypair<S>() -> Result<(BBSplusSecretKey, BBSplusPublicKey), zkryptium::errors::Error>
where
  S: BbsCiphersuite,
{
  KeyPair::<BBSplus<S>>::random().map(KeyPair::into_parts)
}

/// Generates a new BBS+ keypair using either `BLS12381-SHA256` or `BLS12381-SHAKE256`.
pub fn generate_bbs_keypair(alg: ProofAlgorithm) -> KeyStorageResult<(BBSplusSecretKey, BBSplusPublicKey)> {
  match alg {
    ProofAlgorithm::BLS12381_SHA256 => random_bbs_keypair::<Bls12381Sha256>(),
    ProofAlgorithm::BLS12381_SHAKE256 => random_bbs_keypair::<Bls12381Shake256>(),
    _ => return Err(KeyStorageErrorKind::UnsupportedProofAlgorithm.into()),
  }
  .map_err(|err| KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_source(err))
}

/// Encodes a private BBS+ key into JWK.
pub fn encode_bls_jwk(
  private_key: &BBSplusSecretKey,
  public_key: &BBSplusPublicKey,
  alg: ProofAlgorithm,
) -> (Jwk, 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 params = JwkParamsEc {
    x,
    y,
    d: Some(d),
    crv: BlsCurve::BLS12381G2.name().to_owned(),
  };

  let mut jwk = Jwk::from_params(params);

  jwk.set_alg(alg.to_string());
  jwk.set_kid(jwk.thumbprint_sha256_b64());
  let public_jwk = jwk.to_public().expect("kty != oct");

  (jwk, public_jwk)
}

/// Attempts to decode JWK into a BBS+ keypair.
pub fn expand_bls_jwk(jwk: &Jwk) -> KeyStorageResult<(Option<BBSplusSecretKey>, BBSplusPublicKey)> {
  // Check the provided JWK represents a BLS12381G2 key.
  let params = jwk
    .try_ec_params()
    .ok()
    .filter(|params| {
      params
        .try_bls_curve()
        .map(|curve| curve == BlsCurve::BLS12381G2)
        .unwrap_or(false)
    })
    .context(format!("not a {} curve key", BlsCurve::BLS12381G2))
    .map_err(|e| KeyStorageError::new(KeyStorageErrorKind::UnsupportedKeyType).with_source(e))?;

  let sk = params
    .d
    .as_deref()
    .map(|d| {
      jwu::decode_b64(d)
        .context("`d` parameter is not base64 encoded")
        .and_then(|bytes| BBSplusSecretKey::from_bytes(&bytes).context("invalid key size"))
    })
    .transpose()
    .map_err(|e| KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_source(e))?;

  let x = jwu::decode_b64(&params.x)
    .context("`x` parameter is not base64 encoded")
    .and_then(|bytes| bytes.try_into().ok().context("invalid coordinate size"))
    .map_err(|e| KeyStorageError::new(KeyStorageErrorKind::UnsupportedKeyType).with_source(e))?;
  let y = jwu::decode_b64(&params.y)
    .context("`y` parameter is not base64 encoded")
    .and_then(|bytes| bytes.try_into().ok().context("invalid coordinate size"))
    .map_err(|e| KeyStorageError::new(KeyStorageErrorKind::UnsupportedKeyType).with_source(e))?;

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

  Ok((sk, pk))
}

fn _sign_bbs<S>(
  data: &[Vec<u8>],
  sk: &BBSplusSecretKey,
  pk: &BBSplusPublicKey,
  header: &[u8],
) -> Result<Vec<u8>, zkryptium::errors::Error>
where
  S: BbsCiphersuite,
{
  Signature::<BBSplus<S>>::sign(Some(data), sk, pk, Some(header)).map(|s| s.to_bytes().to_vec())
}

/// Signs data and header using the given keys.
pub fn sign_bbs(
  alg: ProofAlgorithm,
  data: &[Vec<u8>],
  sk: &BBSplusSecretKey,
  pk: &BBSplusPublicKey,
  header: &[u8],
) -> KeyStorageResult<Vec<u8>> {
  match alg {
    ProofAlgorithm::BLS12381_SHA256 => _sign_bbs::<Bls12381Sha256>(data, sk, pk, header),
    ProofAlgorithm::BLS12381_SHAKE256 => _sign_bbs::<Bls12381Shake256>(data, sk, pk, header),
    _ => return Err(KeyStorageErrorKind::UnsupportedProofAlgorithm.into()),
  }
  .map_err(|e| {
    KeyStorageError::new(KeyStorageErrorKind::Unspecified)
      .with_source(e)
      .with_custom_message("signature failed".to_owned())
  })
}

fn _update_bbs_signature<S>(
  sig: &[u8; 80],
  sk: &BBSplusSecretKey,
  update_ctx: &ProofUpdateCtx,
) -> Result<[u8; 80], zkryptium::errors::Error>
where
  S: BbsCiphersuite,
{
  let sig = Signature::<BBSplus<S>>::from_bytes(sig)?;
  let ProofUpdateCtx {
    old_start_validity_timeframe,
    new_start_validity_timeframe,
    old_end_validity_timeframe,
    new_end_validity_timeframe,
    index_start_validity_timeframe,
    index_end_validity_timeframe,
    number_of_signed_messages,
  } = update_ctx;
  let half_updated = sig.update_signature(
    sk,
    old_start_validity_timeframe,
    new_start_validity_timeframe,
    *index_start_validity_timeframe,
    *number_of_signed_messages,
  )?;
  half_updated
    .update_signature(
      sk,
      old_end_validity_timeframe,
      new_end_validity_timeframe,
      *index_end_validity_timeframe,
      *number_of_signed_messages,
    )
    .map(|sig| sig.to_bytes())
}

/// Updates BBS+ signature's timeframe data.
pub fn update_bbs_signature(
  alg: ProofAlgorithm,
  sig: &[u8],
  sk: &BBSplusSecretKey,
  update_ctx: &ProofUpdateCtx,
) -> KeyStorageResult<Vec<u8>> {
  let exact_size_signature = sig.try_into().map_err(|_| {
    KeyStorageError::new(KeyStorageErrorKind::Unspecified).with_custom_message("invalid signature size".to_owned())
  })?;
  match alg {
    ProofAlgorithm::BLS12381_SHA256 => _update_bbs_signature::<Bls12381Sha256>(exact_size_signature, sk, update_ctx),
    ProofAlgorithm::BLS12381_SHAKE256 => {
      _update_bbs_signature::<Bls12381Shake256>(exact_size_signature, sk, update_ctx)
    }
    _ => return Err(KeyStorageErrorKind::UnsupportedProofAlgorithm.into()),
  }
  .map(Vec::from)
  .map_err(|e| {
    KeyStorageError::new(KeyStorageErrorKind::Unspecified)
      .with_custom_message("signature failed")
      .with_source(e)
  })
}