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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use bls12_381_plus::*;
use hkdf::HkdfExtract;
use p256::elliptic_curve::group::GroupEncoding;
use crate::{
didcore::{Config, KeyFormat, JWK},
generate_seed,
traits::{DIDCore, Fingerprint, Generate, ECDH},
Document, KeyMaterial, KeyPair, VerificationMethod,
};
pub struct Bls12381KeyPairs {
pk_g1: G1Projective,
pk_g2: G2Projective,
secret_key: Option<Scalar>,
}
impl Bls12381KeyPairs {
fn get_fingerprint_g1(&self) -> String {
let codec: &[u8] = &[0xea, 0x1];
let data = [codec, self.pk_g1.to_bytes().as_ref()].concat().to_vec();
format!("z{}", bs58::encode(data).into_string())
}
fn get_fingerprint_g2(&self) -> String {
let codec: &[u8] = &[0xeb, 0x1];
let data = [codec, self.pk_g2.to_bytes().as_ref()].concat().to_vec();
format!("z{}", bs58::encode(data).into_string())
}
}
impl Generate for Bls12381KeyPairs {
fn new() -> Bls12381KeyPairs {
generate_keypair(None)
}
fn new_with_seed(seed: &[u8]) -> Bls12381KeyPairs {
generate_keypair(Some(seed.into()))
}
fn from_public_key(_public_key: &[u8]) -> Bls12381KeyPairs {
let mut pk_g1 = [0u8; 48];
pk_g1.copy_from_slice(&_public_key[..48]);
let mut pk_g2 = [0u8; 96];
pk_g2.copy_from_slice(&_public_key[48..]);
Bls12381KeyPairs {
pk_g1: G1Projective::from(G1Affine::from_compressed_unchecked(&pk_g1).unwrap()),
pk_g2: G2Projective::from(G2Affine::from_compressed_unchecked(&pk_g2).unwrap()),
secret_key: None,
}
}
fn from_secret_key(secret_key_bytes: &[u8]) -> Bls12381KeyPairs {
let mut bytes: [u8; 32] = [0; 32];
bytes.copy_from_slice(secret_key_bytes);
bytes.reverse();
let sk = Scalar::from_bytes(&bytes).unwrap();
let mut pk_g1 = G1Projective::generator();
pk_g1 *= sk;
let mut pk_g2 = G2Projective::generator();
pk_g2 *= sk;
Bls12381KeyPairs {
pk_g1: pk_g1,
pk_g2: pk_g2,
secret_key: Some(sk),
}
}
}
impl KeyMaterial for Bls12381KeyPairs {
fn public_key_bytes(&self) -> Vec<u8> {
[self.pk_g1.to_bytes().as_ref().to_vec(), self.pk_g2.to_bytes().as_ref().to_vec()]
.concat()
.to_vec()
}
fn private_key_bytes(&self) -> Vec<u8> {
let mut bytes = self.secret_key.unwrap().to_bytes().to_vec();
bytes.reverse();
bytes
}
}
impl DIDCore for Bls12381KeyPairs {
fn get_verification_methods(&self, config: Config, controller: &str) -> Vec<VerificationMethod> {
vec![
VerificationMethod {
id: format!("{}#{}", controller, self.get_fingerprint_g1()),
key_type: match config.use_jose_format {
false => "Bls12381G1Key2020".into(),
true => "JsonWebKey2020".into(),
},
controller: controller.to_string(),
public_key: Some(match config.use_jose_format {
false => KeyFormat::Base58(bs58::encode(self.pk_g1.to_bytes()).into_string()),
true => KeyFormat::JWK(JWK {
key_type: "EC".into(),
curve: "BLS12381_G1".into(),
x: Some(base64::encode_config(self.pk_g1.to_bytes(), base64::URL_SAFE_NO_PAD)),
..Default::default()
}),
}),
private_key: match config.serialize_secrets {
true => self.secret_key.as_ref().map(|_| match config.use_jose_format {
false => KeyFormat::Base58(bs58::encode(self.pk_g1.to_bytes()).into_string()),
true => KeyFormat::JWK(JWK {
key_type: "EC".into(),
curve: "BLS12381_G1".into(),
x: Some(base64::encode_config(self.pk_g1.to_bytes(), base64::URL_SAFE_NO_PAD)),
d: Some(base64::encode_config(self.private_key_bytes(), base64::URL_SAFE_NO_PAD)),
..Default::default()
}),
}),
false => None,
},
..Default::default()
},
VerificationMethod {
id: format!("{}#{}", controller, self.get_fingerprint_g2()),
key_type: match config.use_jose_format {
false => "Bls12381G2Key2020".into(),
true => "JsonWebKey2020".into(),
},
controller: controller.to_string(),
public_key: Some(match config.use_jose_format {
false => KeyFormat::Base58(bs58::encode(self.pk_g2.to_bytes()).into_string()),
true => KeyFormat::JWK(JWK {
key_type: "EC".into(),
curve: "BLS12381_G2".into(),
x: Some(base64::encode_config(self.pk_g2.to_bytes(), base64::URL_SAFE_NO_PAD)),
..Default::default()
}),
}),
private_key: match config.serialize_secrets {
true => self.secret_key.as_ref().map(|_| match config.use_jose_format {
false => KeyFormat::Base58(bs58::encode(self.private_key_bytes()).into_string()),
true => KeyFormat::JWK(JWK {
key_type: "EC".into(),
curve: "BLS12381_G2".into(),
x: Some(base64::encode_config(self.pk_g2.to_bytes(), base64::URL_SAFE_NO_PAD)),
d: Some(base64::encode_config(self.private_key_bytes(), base64::URL_SAFE_NO_PAD)),
..Default::default()
}),
}),
false => None,
},
..Default::default()
},
]
}
fn get_did_document(&self, config: Config) -> crate::Document {
let fingerprint = self.fingerprint();
let controller = format!("did:key:{}", fingerprint.clone());
let vm = &self.get_verification_methods(config, &controller);
let vm_ids: Vec<String> = vm.iter().map(|x| x.id.to_string()).collect();
Document {
context: "https://www.w3.org/ns/did/v1".to_string(),
id: controller.to_string(),
key_agreement: None,
authentication: Some(vm_ids.clone()),
assertion_method: Some(vm_ids.clone()),
capability_delegation: Some(vm_ids.clone()),
capability_invocation: Some(vm_ids.clone()),
verification_method: vm.clone(),
}
}
}
impl Fingerprint for Bls12381KeyPairs {
fn fingerprint(&self) -> String {
let codec: &[u8] = &[0xee, 0x1];
let data = [codec, self.pk_g1.to_bytes().as_ref(), self.pk_g2.to_bytes().as_ref()].concat().to_vec();
format!("z{}", bs58::encode(data).into_string())
}
}
impl ECDH for Bls12381KeyPairs {
fn key_exchange(&self, _: &Self) -> Vec<u8> {
unimplemented!("ECDH is not supported for this key type")
}
}
impl From<Bls12381KeyPairs> for KeyPair {
fn from(key_pair: Bls12381KeyPairs) -> Self {
KeyPair::Bls12381G1G2(key_pair)
}
}
fn generate_keypair(seed: Option<Vec<u8>>) -> Bls12381KeyPairs {
let seed_data = generate_seed(seed.map_or(vec![], |x| x).as_slice()).unwrap();
let sk = gen_sk(seed_data.to_vec().as_slice()).unwrap();
let mut pk_g1 = G1Projective::generator();
pk_g1 *= sk;
let mut pk_g2 = G2Projective::generator();
pk_g2 *= sk;
Bls12381KeyPairs {
pk_g1: pk_g1,
pk_g2: pk_g2,
secret_key: Some(sk),
}
}
fn gen_sk(ikm: &[u8]) -> Option<Scalar> {
const SALT: &'static [u8] = b"BLS-SIG-KEYGEN-SALT-";
const INFO: [u8; 2] = [0u8, 48u8];
let mut extracter = HkdfExtract::<sha2::Sha256>::new(Some(SALT));
extracter.input_ikm(ikm);
extracter.input_ikm(&[0u8]);
let (_, h) = extracter.finalize();
let mut output = [0u8; 48];
if let Err(_) = h.expand(&INFO, &mut output) {
None
} else {
Some(Scalar::from_okm(&output))
}
}
#[cfg(test)]
pub mod test {
use super::*;
use crate::{CONFIG_LD_PRIVATE, CONFIG_LD_PUBLIC};
#[test]
fn test_public_key() {
let keypair = generate_keypair(None);
let from = Bls12381KeyPairs::from_public_key(&keypair.public_key_bytes());
assert!(from.pk_g1.eq(&keypair.pk_g1));
assert!(from.pk_g2.eq(&keypair.pk_g2));
}
#[test]
fn test_generate_public_key() {
let key = Bls12381KeyPairs::new_with_seed(vec![].as_slice());
let pk = key.public_key_bytes();
assert_eq!(48 + 96, pk.len());
}
#[test]
fn test_generate_public_key_from_bytes() {
let key = Bls12381KeyPairs::new_with_seed(vec![].as_slice());
let pk = key.public_key_bytes();
let actual = Bls12381KeyPairs::from_public_key(&pk);
let pk1 = actual.public_key_bytes();
assert_eq!(pk, pk1);
}
#[test]
fn test_resolve() {
let key = Bls12381KeyPairs::new();
let doc = key.get_did_document(CONFIG_LD_PRIVATE);
let g2 = doc.authentication.unwrap()[1].clone();
let resolved = crate::resolve(g2.as_str());
let doc2 = resolved.unwrap().get_did_document(CONFIG_LD_PRIVATE);
assert_eq!(doc.id, doc2.id)
}
#[test]
fn secret_key_size() {
let key = Bls12381KeyPairs::new();
let sk_bytes = key.private_key_bytes();
assert_eq!(sk_bytes.len(), 32);
let key = Bls12381KeyPairs::from_secret_key(&sk_bytes);
assert_eq!(key.private_key_bytes().len(), 32)
}
#[test]
fn test_did_doc() {
let key = Bls12381KeyPairs::new();
let json = key.get_did_document(CONFIG_LD_PRIVATE);
assert!(json.verification_method[0].private_key.is_some());
println!("{}", serde_json::to_string_pretty(&json).unwrap());
let json = key.get_did_document(CONFIG_LD_PUBLIC);
assert!(json.verification_method[0].private_key.is_none());
}
}