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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! multicodec key parsing
//!
//! parses multicodec-prefixed public keys from DID documents, and the
//! private-key multikeys atproto implementations use to store signing and
//! rotation keys. extracts key type and raw key bytes.
//!
//! see: https://github.com/multiformats/multicodec
const std = @import("std");
/// supported key types for AT Protocol
pub const KeyType = enum {
secp256k1, // ES256K - used by most AT Protocol accounts
p256, // ES256 - also supported
};
/// parsed public key with type and raw bytes
pub const PublicKey = struct {
key_type: KeyType,
/// raw compressed public key (33 bytes for secp256k1/p256)
raw: []const u8,
};
/// multicodec prefixes (unsigned varint encoding)
/// secp256k1-pub: 0xe7 = 231, varint encoded as 0xe7 0x01 (2 bytes)
/// p256-pub: 0x1200 = 4608, varint encoded as 0x80 0x24 (2 bytes)
/// parse a multicodec-prefixed public key
/// returns the key type and a slice pointing to the raw key bytes
pub fn parsePublicKey(data: []const u8) !PublicKey {
if (data.len < 2) return error.TooShort;
// check for secp256k1-pub (varint 0xe7 = 231 encoded as 0xe7 0x01)
if (data.len >= 2 and data[0] == 0xe7 and data[1] == 0x01) {
const raw = data[2..];
if (raw.len != 33) return error.InvalidKeyLength;
return .{
.key_type = .secp256k1,
.raw = raw,
};
}
// check for p256-pub (varint 0x1200 = 4608 encoded as 0x80 0x24)
if (data.len >= 2 and data[0] == 0x80 and data[1] == 0x24) {
const raw = data[2..];
if (raw.len != 33) return error.InvalidKeyLength;
return .{
.key_type = .p256,
.raw = raw,
};
}
return error.UnsupportedKeyType;
}
/// parsed private key with type and raw scalar bytes
pub const PrivateKey = struct {
key_type: KeyType,
/// raw 32-byte big-endian secret scalar
raw: [32]u8,
};
/// secp256k1-priv: multicodec 0x1301, varint 0x81 0x26
const secp256k1_priv_prefix = [2]u8{ 0x81, 0x26 };
/// p256-priv: multicodec 0x1306, varint 0x86 0x26
const p256_priv_prefix = [2]u8{ 0x86, 0x26 };
/// parse multicodec-prefixed private key bytes (secp256k1-priv or p256-priv
/// followed by the 32-byte scalar). does not check the scalar is in range;
/// `Keypair.fromSecretKey` does.
pub fn parsePrivateKey(data: []const u8) !PrivateKey {
if (data.len < 2) return error.TooShort;
const key_type: KeyType = if (std.mem.eql(u8, data[0..2], &secp256k1_priv_prefix))
.secp256k1
else if (std.mem.eql(u8, data[0..2], &p256_priv_prefix))
.p256
else
return error.UnsupportedKeyType;
if (data.len != 2 + 32) return error.InvalidKeyLength;
return .{ .key_type = key_type, .raw = data[2..34].* };
}
/// encode a raw private key with its multicodec prefix
pub fn encodePrivateKey(key_type: KeyType, raw: *const [32]u8) [34]u8 {
var out: [34]u8 = undefined;
out[0..2].* = switch (key_type) {
.secp256k1 => secp256k1_priv_prefix,
.p256 => p256_priv_prefix,
};
out[2..].* = raw.*;
return out;
}
/// parse a base58btc private multikey ("z..."), as produced by indigo's and
/// @atproto/crypto's private-key `Multibase()` / export. the decoded buffer is
/// zeroed before it is freed.
pub fn parsePrivateMultikey(allocator: std.mem.Allocator, text: []const u8) !PrivateKey {
const multibase = @import("multibase.zig");
if (text.len < 2 or text[0] != 'z') return error.InvalidMultikey;
const decoded = multibase.base58btc.decode(allocator, text[1..]) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidMultikey,
};
defer {
std.crypto.secureZero(u8, decoded);
allocator.free(decoded);
}
return parsePrivateKey(decoded);
}
/// format a raw private key as a base58btc private multikey ("z...").
/// caller owns the returned slice and should zero it when done.
pub fn formatPrivateMultikey(allocator: std.mem.Allocator, key_type: KeyType, raw: *const [32]u8) ![]u8 {
const multibase = @import("multibase.zig");
var bytes = encodePrivateKey(key_type, raw);
defer std.crypto.secureZero(u8, &bytes);
return multibase.base58btc.encode(allocator, &bytes);
}
/// encode a raw public key with multicodec prefix
pub fn encodePublicKey(allocator: std.mem.Allocator, key_type: KeyType, raw: []const u8) ![]u8 {
if (raw.len != 33) return error.InvalidKeyLength;
const result = try allocator.alloc(u8, 2 + raw.len);
switch (key_type) {
.secp256k1 => {
result[0] = 0xe7;
result[1] = 0x01;
},
.p256 => {
result[0] = 0x80;
result[1] = 0x24;
},
}
@memcpy(result[2..], raw);
return result;
}
/// format a raw public key as a did:key string
pub fn formatDidKey(allocator: std.mem.Allocator, key_type: KeyType, raw: []const u8) ![]u8 {
const multibase = @import("multibase.zig");
const mc_bytes = try encodePublicKey(allocator, key_type, raw);
defer allocator.free(mc_bytes);
const multibase_str = try multibase.encode(allocator, .base58btc, mc_bytes);
defer allocator.free(multibase_str);
// "did:key:" + multibase string (which already has 'z' prefix)
const result = try allocator.alloc(u8, did_key_prefix.len + multibase_str.len);
@memcpy(result[0..did_key_prefix.len], did_key_prefix);
@memcpy(result[did_key_prefix.len..], multibase_str);
return result;
}
const did_key_prefix = "did:key:";
/// parse a did:key string into key type and raw public key bytes.
/// caller owns the returned slice (raw field).
pub fn parseDidKey(allocator: std.mem.Allocator, did: []const u8) !struct { key_type: KeyType, raw: []u8 } {
const multibase = @import("multibase.zig");
if (!std.mem.startsWith(u8, did, did_key_prefix)) return error.InvalidDidKey;
const multibase_str = did[did_key_prefix.len..];
if (multibase_str.len == 0) return error.InvalidDidKey;
const mc_bytes = try multibase.decode(allocator, multibase_str);
defer allocator.free(mc_bytes);
const parsed = try parsePublicKey(mc_bytes);
const raw = try allocator.dupe(u8, parsed.raw);
return .{ .key_type = parsed.key_type, .raw = raw };
}
/// verify an ECDSA signature given a did:key string.
/// dispatches to the correct curve based on the key type encoded in the did:key.
pub fn verifyDidKeySignature(allocator: std.mem.Allocator, did: []const u8, message: []const u8, sig_bytes: []const u8) !void {
const jwt = @import("jwt.zig");
const parsed = try parseDidKey(allocator, did);
defer allocator.free(parsed.raw);
switch (parsed.key_type) {
.secp256k1 => try jwt.verifySecp256k1(message, sig_bytes, parsed.raw),
.p256 => try jwt.verifyP256(message, sig_bytes, parsed.raw),
}
}
// === tests ===
test "parse secp256k1 key" {
// 0xe7 0x01 prefix (varint) + 33-byte compressed key
var data: [35]u8 = undefined;
data[0] = 0xe7;
data[1] = 0x01;
data[2] = 0x02; // compressed point prefix
@memset(data[3..], 0xaa);
const key = try parsePublicKey(&data);
try std.testing.expectEqual(KeyType.secp256k1, key.key_type);
try std.testing.expectEqual(@as(usize, 33), key.raw.len);
}
test "parse p256 key" {
// 0x80 0x24 prefix + 33-byte compressed key
var data: [35]u8 = undefined;
data[0] = 0x80;
data[1] = 0x24;
data[2] = 0x03; // compressed point prefix
@memset(data[3..], 0xbb);
const key = try parsePublicKey(&data);
try std.testing.expectEqual(KeyType.p256, key.key_type);
try std.testing.expectEqual(@as(usize, 33), key.raw.len);
}
test "reject unsupported key type" {
const data = [_]u8{ 0xff, 0x02, 0x00 };
try std.testing.expectError(error.UnsupportedKeyType, parsePublicKey(&data));
}
test "reject too short" {
const data = [_]u8{0xe7};
try std.testing.expectError(error.TooShort, parsePublicKey(&data));
}
test "private multikey round-trips indigo's fixtures" {
// atproto/atcrypto/keys_test.go TestParsePrivateMultibase
const alloc = std.testing.allocator;
const cases = [_]struct { text: []const u8, key_type: KeyType }{
.{ .text = "z42tvqQS5sVhaV1jLZ5P6ZKEPEbSpYavNVmT88YDYV3MEZ8D", .key_type = .p256 },
.{ .text = "z3vLWgA9nXoPzxsJJafDY9BPrZd3EDWjvcCtYfrFxZ7xbMVi", .key_type = .secp256k1 },
};
for (cases) |case| {
const parsed = try parsePrivateMultikey(alloc, case.text);
try std.testing.expectEqual(case.key_type, parsed.key_type);
const again = try formatPrivateMultikey(alloc, parsed.key_type, &parsed.raw);
defer alloc.free(again);
try std.testing.expectEqualStrings(case.text, again);
}
}
test "private key codec uses the multicodec table's varints" {
const raw: [32]u8 = @splat(0x11);
const k = encodePrivateKey(.secp256k1, &raw);
try std.testing.expectEqualSlices(u8, &.{ 0x81, 0x26 }, k[0..2]);
const p = encodePrivateKey(.p256, &raw);
try std.testing.expectEqualSlices(u8, &.{ 0x86, 0x26 }, p[0..2]);
try std.testing.expectEqual(KeyType.p256, (try parsePrivateKey(&p)).key_type);
}
test "private key parsing rejects public keys, bad lengths and other bases" {
const alloc = std.testing.allocator;
var data: [35]u8 = undefined;
data[0] = 0xe7;
data[1] = 0x01;
@memset(data[2..], 0x02);
try std.testing.expectError(error.UnsupportedKeyType, parsePrivateKey(&data));
data[0] = 0x81;
data[1] = 0x26;
try std.testing.expectError(error.InvalidKeyLength, parsePrivateKey(&data));
try std.testing.expectError(error.InvalidKeyLength, parsePrivateKey(data[0..33]));
try std.testing.expectError(error.TooShort, parsePrivateKey(data[0..1]));
// a public multikey is not a private one
try std.testing.expectError(
error.UnsupportedKeyType,
parsePrivateMultikey(alloc, "zQ3shscXNYZQZSPwegiv7uQZZV5kzATLBRtgJhs7uRY7pfSk4"),
);
try std.testing.expectError(error.InvalidMultikey, parsePrivateMultikey(alloc, "b3vLWgA9nXoPzxsJ"));
try std.testing.expectError(error.InvalidMultikey, parsePrivateMultikey(alloc, "z0OIl"));
try std.testing.expectError(error.InvalidMultikey, parsePrivateMultikey(alloc, "z"));
}
test "encode-decode round-trip secp256k1" {
const alloc = std.testing.allocator;
var raw: [33]u8 = undefined;
raw[0] = 0x02;
@memset(raw[1..], 0xaa);
const encoded = try encodePublicKey(alloc, .secp256k1, &raw);
defer alloc.free(encoded);
const parsed = try parsePublicKey(encoded);
try std.testing.expectEqual(KeyType.secp256k1, parsed.key_type);
try std.testing.expectEqualSlices(u8, &raw, parsed.raw);
}
test "did:key round-trip secp256k1" {
const alloc = std.testing.allocator;
const multibase = @import("multibase.zig");
var raw: [33]u8 = undefined;
raw[0] = 0x02;
@memset(raw[1..], 0xcc);
const did_key_str = try formatDidKey(alloc, .secp256k1, &raw);
defer alloc.free(did_key_str);
// should start with "did:key:z"
try std.testing.expect(std.mem.startsWith(u8, did_key_str, "did:key:z"));
// parse back: strip "did:key:" prefix, decode multibase, parse multicodec
const multibase_str = did_key_str["did:key:".len..];
const mc_bytes = try multibase.decode(alloc, multibase_str);
defer alloc.free(mc_bytes);
const parsed = try parsePublicKey(mc_bytes);
try std.testing.expectEqual(KeyType.secp256k1, parsed.key_type);
try std.testing.expectEqualSlices(u8, &raw, parsed.raw);
}
test "did:key round-trip p256" {
const alloc = std.testing.allocator;
const multibase = @import("multibase.zig");
var raw: [33]u8 = undefined;
raw[0] = 0x03;
@memset(raw[1..], 0xdd);
const did_key_str = try formatDidKey(alloc, .p256, &raw);
defer alloc.free(did_key_str);
const multibase_str = did_key_str["did:key:".len..];
const mc_bytes = try multibase.decode(alloc, multibase_str);
defer alloc.free(mc_bytes);
const parsed = try parsePublicKey(mc_bytes);
try std.testing.expectEqual(KeyType.p256, parsed.key_type);
try std.testing.expectEqualSlices(u8, &raw, parsed.raw);
}
test "parseDidKey round-trip secp256k1" {
const alloc = std.testing.allocator;
var raw: [33]u8 = undefined;
raw[0] = 0x02;
@memset(raw[1..], 0xcc);
const did_str = try formatDidKey(alloc, .secp256k1, &raw);
defer alloc.free(did_str);
const parsed = try parseDidKey(alloc, did_str);
defer alloc.free(parsed.raw);
try std.testing.expectEqual(KeyType.secp256k1, parsed.key_type);
try std.testing.expectEqualSlices(u8, &raw, parsed.raw);
}
test "parseDidKey round-trip p256" {
const alloc = std.testing.allocator;
var raw: [33]u8 = undefined;
raw[0] = 0x03;
@memset(raw[1..], 0xdd);
const did_str = try formatDidKey(alloc, .p256, &raw);
defer alloc.free(did_str);
const parsed = try parseDidKey(alloc, did_str);
defer alloc.free(parsed.raw);
try std.testing.expectEqual(KeyType.p256, parsed.key_type);
try std.testing.expectEqualSlices(u8, &raw, parsed.raw);
}
test "parseDidKey with real indigo test vector" {
// from bluesky-social/indigo jwt test fixtures
const alloc = std.testing.allocator;
const parsed = try parseDidKey(alloc, "did:key:zQ3shscXNYZQZSPwegiv7uQZZV5kzATLBRtgJhs7uRY7pfSk4");
defer alloc.free(parsed.raw);
try std.testing.expectEqual(KeyType.secp256k1, parsed.key_type);
try std.testing.expectEqual(@as(usize, 33), parsed.raw.len);
try std.testing.expect(parsed.raw[0] == 0x02 or parsed.raw[0] == 0x03);
}
test "parseDidKey rejects invalid prefix" {
const alloc = std.testing.allocator;
try std.testing.expectError(error.InvalidDidKey, parseDidKey(alloc, "did:web:example.com"));
try std.testing.expectError(error.InvalidDidKey, parseDidKey(alloc, "did:key:"));
try std.testing.expectError(error.InvalidDidKey, parseDidKey(alloc, ""));
}
test "verifyDidKeySignature secp256k1" {
const alloc = std.testing.allocator;
const jwt = @import("jwt.zig");
const crypto = std.crypto;
const Scheme = crypto.sign.ecdsa.EcdsaSecp256k1Sha256;
const sk_bytes = [_]u8{
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
};
const message = "verify via did:key";
const sig = try jwt.signSecp256k1(message, &sk_bytes);
// derive public key and format as did:key
const sk = try Scheme.SecretKey.fromBytes(sk_bytes);
const kp = try Scheme.KeyPair.fromSecretKey(sk);
const pk_bytes = kp.public_key.toCompressedSec1();
const did = try formatDidKey(alloc, .secp256k1, &pk_bytes);
defer alloc.free(did);
// should verify
try verifyDidKeySignature(alloc, did, message, &sig.bytes);
// should reject wrong message
try std.testing.expectError(
error.SignatureVerificationFailed,
verifyDidKeySignature(alloc, did, "wrong message", &sig.bytes),
);
}