aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib.zig')
-rw-r--r--src/lib.zig729
1 files changed, 0 insertions, 729 deletions
diff --git a/src/lib.zig b/src/lib.zig
deleted file mode 100644
index 23f0e05..0000000
--- a/src/lib.zig
+++ /dev/null
@@ -1,729 +0,0 @@
1const std = @import("std");
2const ascii = std.ascii;
3const base32 = @import("base32.zig");
4const crc16 = @import("crc16.zig");
5const crypto = std.crypto;
6const Ed25519 = crypto.sign.Ed25519;
7const mem = std.mem;
8const testing = std.testing;
9
10pub const InvalidPrefixByteError = error{InvalidPrefixByte};
11pub const InvalidEncodingError = error{InvalidEncoding};
12pub const InvalidPrivateKeyError = error{InvalidPrivateKey};
13pub const InvalidSeedError = error{InvalidSeed};
14pub const InvalidSignatureError = error{InvalidSignature};
15pub const NoNkeySeedFoundError = error{NoNkeySeedFound};
16pub const NoNkeyUserSeedFoundError = error{NoNkeyUserSeedFound};
17pub const DecodeError = InvalidPrefixByteError || base32.DecodeError || crc16.InvalidChecksumError;
18pub const SeedDecodeError = DecodeError || InvalidSeedError || crypto.errors.IdentityElementError;
19pub const PrivateKeyDecodeError = DecodeError || InvalidPrivateKeyError || crypto.errors.IdentityElementError;
20pub const SignError = crypto.errors.IdentityElementError || crypto.errors.WeakPublicKeyError || crypto.errors.KeyMismatchError;
21
22pub const prefix_byte_account = 0; // A
23pub const prefix_byte_cluster = 2 << 3; // C
24pub const prefix_byte_operator = 14 << 3; // O
25pub const prefix_byte_private = 15 << 3; // P
26pub const prefix_byte_seed = 18 << 3; // S
27pub const prefix_byte_server = 13 << 3; // N
28pub const prefix_byte_user = 20 << 3; // U
29
30pub fn prefixByteToLetter(prefix_byte: u8) ?u8 {
31 return switch (prefix_byte) {
32 prefix_byte_account => 'A',
33 prefix_byte_cluster => 'C',
34 prefix_byte_operator => 'O',
35 prefix_byte_private => 'P',
36 prefix_byte_seed => 'S',
37 prefix_byte_server => 'N',
38 prefix_byte_user => 'U',
39 else => null,
40 };
41}
42
43pub fn prefixByteFromLetter(letter: u8) ?u8 {
44 return switch (letter) {
45 'A' => prefix_byte_account,
46 'C' => prefix_byte_cluster,
47 'O' => prefix_byte_operator,
48 'P' => prefix_byte_private,
49 'S' => prefix_byte_seed,
50 'N' => prefix_byte_server,
51 'U' => prefix_byte_user,
52 else => null,
53 };
54}
55
56pub const Role = enum(u8) {
57 const Self = @This();
58
59 account,
60 cluster,
61 operator,
62 server,
63 user,
64
65 pub fn fromPublicPrefixByte(b: u8) ?Self {
66 return switch (b) {
67 prefix_byte_account => .account,
68 prefix_byte_cluster => .cluster,
69 prefix_byte_operator => .operator,
70 prefix_byte_server => .server,
71 prefix_byte_user => .user,
72 else => null,
73 };
74 }
75
76 pub fn publicPrefixByte(self: Self) u8 {
77 return switch (self) {
78 .account => prefix_byte_account,
79 .cluster => prefix_byte_cluster,
80 .operator => prefix_byte_operator,
81 .server => prefix_byte_server,
82 .user => prefix_byte_user,
83 };
84 }
85
86 pub fn letter(self: Self) u8 {
87 return prefixByteToLetter(self.publicPrefixByte()) orelse unreachable;
88 }
89};
90
91// One prefix byte, two CRC bytes
92const binary_private_size = 1 + Ed25519.secret_length + 2;
93// One prefix byte, two CRC bytes
94const binary_public_size = 1 + Ed25519.public_length + 2;
95// Two prefix bytes, two CRC bytes
96const binary_seed_size = 2 + Ed25519.seed_length + 2;
97
98pub const text_private_len = base32.Encoder.calcSize(binary_private_size);
99pub const text_public_len = base32.Encoder.calcSize(binary_public_size);
100pub const text_seed_len = base32.Encoder.calcSize(binary_seed_size);
101
102pub const text_private = [text_private_len]u8;
103pub const text_public = [text_public_len]u8;
104pub const text_seed = [text_seed_len]u8;
105
106pub const SeedKeyPair = struct {
107 const Self = @This();
108
109 role: Role,
110 kp: Ed25519.KeyPair,
111
112 pub fn generate(role: Role) crypto.errors.IdentityElementError!Self {
113 var raw_seed: [Ed25519.seed_length]u8 = undefined;
114 crypto.random.bytes(&raw_seed);
115 defer wipeBytes(&raw_seed);
116 return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed) };
117 }
118
119 pub fn generateWithCustomEntropy(role: Role, reader: anytype) !Self {
120 var raw_seed: [Ed25519.seed_length]u8 = undefined;
121 try reader.readNoEof(&raw_seed);
122 defer wipeBytes(&raw_seed);
123 return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed) };
124 }
125
126 pub fn fromTextSeed(text: *const text_seed) SeedDecodeError!Self {
127 var decoded = try decode(2, Ed25519.seed_length, text);
128 defer decoded.wipe(); // gets copied
129
130 var key_ty_prefix = decoded.prefix[0] & 0b11111000;
131 var role_prefix = (decoded.prefix[0] << 5) | (decoded.prefix[1] >> 3);
132
133 if (key_ty_prefix != prefix_byte_seed)
134 return error.InvalidSeed;
135
136 return Self{
137 .role = Role.fromPublicPrefixByte(role_prefix) orelse return error.InvalidPrefixByte,
138 .kp = try Ed25519.KeyPair.create(decoded.data),
139 };
140 }
141
142 pub fn fromRawSeed(
143 role: Role,
144 raw_seed: *const [Ed25519.seed_length]u8,
145 ) crypto.errors.IdentityElementError!Self {
146 return Self{ .role = role, .kp = try Ed25519.KeyPair.create(raw_seed.*) };
147 }
148
149 pub fn sign(self: *const Self, msg: []const u8) SignError![Ed25519.signature_length]u8 {
150 return Ed25519.sign(msg, self.kp, null);
151 }
152
153 pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void {
154 Ed25519.verify(sig, msg, self.kp.public_key) catch return error.InvalidSignature;
155 }
156
157 pub fn seedText(self: *const Self) text_seed {
158 const public_prefix = self.role.publicPrefixByte();
159 const full_prefix = &[_]u8{
160 prefix_byte_seed | (public_prefix >> 5),
161 (public_prefix & 0b00011111) << 3,
162 };
163 const seed = self.kp.secret_key[0..Ed25519.seed_length];
164 return encode(full_prefix.len, seed.len, full_prefix, seed);
165 }
166
167 pub fn privateKeyText(self: *const Self) text_private {
168 return encode(1, self.kp.secret_key.len, &.{prefix_byte_private}, &self.kp.secret_key);
169 }
170
171 pub fn publicKeyText(self: *const Self) text_public {
172 return encode(1, self.kp.public_key.len, &.{self.role.publicPrefixByte()}, &self.kp.public_key);
173 }
174
175 pub fn intoPublicKey(self: *const Self) PublicKey {
176 return PublicKey{
177 .role = self.role,
178 .key = self.kp.public_key,
179 };
180 }
181
182 pub fn intoPrivateKey(self: *const Self) PrivateKey {
183 return PrivateKey{ .kp = self.kp };
184 }
185
186 pub fn wipe(self: *Self) void {
187 self.role = .account;
188 wipeKeyPair(&self.kp);
189 }
190};
191
192pub const PublicKey = struct {
193 const Self = @This();
194
195 role: Role,
196 key: [Ed25519.public_length]u8,
197
198 pub fn fromTextPublicKey(text: *const text_public) DecodeError!Self {
199 var decoded = try decode(1, Ed25519.public_length, text);
200 defer decoded.wipe(); // gets copied
201 return PublicKey{
202 .role = Role.fromPublicPrefixByte(decoded.prefix[0]) orelse return error.InvalidPrefixByte,
203 .key = decoded.data,
204 };
205 }
206
207 pub fn fromRawPublicKey(role: Role, raw_key: *const [Ed25519.public_length]u8) Self {
208 return Self{ .role = role, .key = raw_key.* };
209 }
210
211 pub fn publicKeyText(self: *const Self) text_public {
212 return encode(1, self.key.len, &.{self.role.publicPrefixByte()}, &self.key);
213 }
214
215 pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void {
216 Ed25519.verify(sig, msg, self.key) catch return error.InvalidSignature;
217 }
218
219 pub fn wipe(self: *Self) void {
220 self.role = .account;
221 wipeBytes(&self.key);
222 }
223};
224
225pub const PrivateKey = struct {
226 const Self = @This();
227
228 kp: Ed25519.KeyPair,
229
230 pub fn fromTextPrivateKey(text: *const text_private) PrivateKeyDecodeError!Self {
231 var decoded = try decode(1, Ed25519.secret_length, text);
232 defer decoded.wipe(); // gets copied
233 if (decoded.prefix[0] != prefix_byte_private)
234 return error.InvalidPrivateKey;
235 return PrivateKey{ .kp = Ed25519.KeyPair.fromSecretKey(decoded.data) };
236 }
237
238 pub fn fromRawPrivateKey(raw_key: *const [Ed25519.secret_length]u8) Self {
239 return Self{ .kp = Ed25519.KeyPair.fromSecretKey(raw_key.*) };
240 }
241
242 pub fn intoSeedKeyPair(self: *const Self, role: Role) SeedKeyPair {
243 return SeedKeyPair{
244 .role = role,
245 .kp = self.kp,
246 };
247 }
248
249 pub fn intoPublicKey(self: *const Self, role: Role) PublicKey {
250 return PublicKey{
251 .role = role,
252 .key = self.kp.public_key,
253 };
254 }
255
256 pub fn privateKeyText(self: *const Self) text_private {
257 return encode(1, self.kp.secret_key.len, &.{prefix_byte_private}, &self.kp.secret_key);
258 }
259
260 pub fn sign(self: *const Self, msg: []const u8) SignError![Ed25519.signature_length]u8 {
261 return Ed25519.sign(msg, self.kp, null);
262 }
263
264 pub fn verify(self: *const Self, msg: []const u8, sig: [Ed25519.signature_length]u8) InvalidSignatureError!void {
265 Ed25519.verify(sig, msg, self.kp.public_key) catch return error.InvalidSignature;
266 }
267
268 pub fn wipe(self: *Self) void {
269 wipeKeyPair(&self.kp);
270 }
271};
272
273fn encoded_key(comptime prefix_len: usize, comptime data_len: usize) type {
274 return [base32.Encoder.calcSize(prefix_len + data_len + 2)]u8;
275}
276
277fn encode(
278 comptime prefix_len: usize,
279 comptime data_len: usize,
280 prefix: *const [prefix_len]u8,
281 data: *const [data_len]u8,
282) encoded_key(prefix_len, data_len) {
283 var buf: [prefix_len + data_len + 2]u8 = undefined;
284 defer wipeBytes(&buf);
285
286 mem.copy(u8, &buf, prefix[0..]);
287 mem.copy(u8, buf[prefix_len..], data[0..]);
288 var off = prefix_len + data_len;
289 var checksum = crc16.make(buf[0..off]);
290 mem.writeIntLittle(u16, buf[buf.len - 2 .. buf.len], checksum);
291
292 var text: encoded_key(prefix_len, data_len) = undefined;
293 std.debug.assert(base32.Encoder.encode(&text, &buf).len == text.len);
294
295 return text;
296}
297
298fn DecodedNkey(comptime prefix_len: usize, comptime data_len: usize) type {
299 return struct {
300 const Self = @This();
301
302 prefix: [prefix_len]u8,
303 data: [data_len]u8,
304
305 pub fn wipe(self: *Self) void {
306 self.prefix[0] = Role.account.publicPrefixByte();
307 wipeBytes(&self.data);
308 }
309 };
310}
311
312fn decode(
313 comptime prefix_len: usize,
314 comptime data_len: usize,
315 text: *const [base32.Encoder.calcSize(prefix_len + data_len + 2)]u8,
316) (base32.DecodeError || crc16.InvalidChecksumError)!DecodedNkey(prefix_len, data_len) {
317 var raw: [prefix_len + data_len + 2]u8 = undefined;
318 defer wipeBytes(&raw);
319 std.debug.assert((try base32.Decoder.decode(&raw, text[0..])).len == raw.len);
320
321 var checksum = mem.readIntLittle(u16, raw[raw.len - 2 .. raw.len]);
322 try crc16.validate(raw[0 .. raw.len - 2], checksum);
323
324 return DecodedNkey(prefix_len, data_len){
325 .prefix = raw[0..prefix_len].*,
326 .data = raw[prefix_len .. raw.len - 2].*,
327 };
328}
329
330pub fn isValidEncoding(text: []const u8) bool {
331 if (text.len < 4) return false;
332 var made_crc: u16 = 0;
333 var dec = base32.Decoder.init(text);
334 var crc_buf: [2]u8 = undefined;
335 var crc_buf_len: u8 = 0;
336 var expect_len: usize = base32.Decoder.calcSize(text.len);
337 var wrote_n_total: usize = 0;
338 while (dec.next() catch return false) |b| {
339 wrote_n_total += 1;
340 if (crc_buf_len == 2) made_crc = crc16.update(made_crc, &.{crc_buf[0]});
341 crc_buf[0] = crc_buf[1];
342 crc_buf[1] = b;
343 if (crc_buf_len != 2) crc_buf_len += 1;
344 }
345 std.debug.assert(wrote_n_total == expect_len);
346 if (crc_buf_len != 2) unreachable;
347 var got_crc = mem.readIntLittle(u16, &crc_buf);
348 return made_crc == got_crc;
349}
350
351pub fn isValidSeed(text: []const u8, with_role: ?Role) bool {
352 if (text.len < text_seed_len) return false;
353 var res = SeedKeyPair.fromTextSeed(text[0..text_seed_len]) catch return false;
354 defer res.wipe();
355 return if (with_role) |role| res.role == role else true;
356}
357
358pub fn isValidPublicKey(text: []const u8, with_role: ?Role) bool {
359 if (text.len < text_public_len) return false;
360 var res = PublicKey.fromTextPublicKey(text[0..text_public_len]) catch return false;
361 defer res.wipe();
362 return if (with_role) |role| res.role == role else true;
363}
364
365pub fn isValidPrivateKey(text: []const u8) bool {
366 if (text.len < text_private_len) return false;
367 var res = PrivateKey.fromTextPrivateKey(text[0..text_private_len]) catch return false;
368 res.wipe();
369 return true;
370}
371
372// `line` must not contain CR or LF characters.
373pub fn isKeySectionBarrier(line: []const u8, opening: bool) bool {
374 if (line.len < 6) return false;
375 const start = mem.indexOf(u8, line, "---") orelse return false;
376 if (!opening and start != 0) return false;
377 if (line.len - start < 6) return false;
378 return mem.endsWith(u8, line, "---");
379}
380
381const allowed_creds_section_chars_table: [256]bool = allowed: {
382 var table = [_]bool{false} ** 256;
383 const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.=";
384 for (chars) |char| table[char] = true;
385 break :allowed table;
386};
387
388pub fn areKeySectionContentsValid(contents: []const u8) bool {
389 for (contents) |c| if (!allowed_creds_section_chars_table[c]) return false;
390 return true;
391}
392
393pub fn findKeySection(text: []const u8, line_it: *std.mem.SplitIterator) ?[]const u8 {
394 while (true) {
395 const opening_line = line_it.next() orelse return null;
396 if (!isKeySectionBarrier(opening_line, true)) continue;
397
398 const contents_line = line_it.next() orelse return null;
399 if (!areKeySectionContentsValid(contents_line)) continue;
400
401 const closing_line = line_it.next() orelse return null;
402 if (!isKeySectionBarrier(closing_line, false)) continue;
403
404 return contents_line;
405 }
406}
407
408pub fn parseDecoratedJwt(contents: []const u8) []const u8 {
409 var line_it = mem.split(contents, "\n");
410 return findKeySection(contents, &line_it) orelse return contents;
411}
412
413pub fn parseDecoratedNkey(contents: []const u8) NoNkeySeedFoundError!SeedKeyPair {
414 var line_it = mem.split(contents, "\n");
415 var current_off: usize = 0;
416 var seed: ?[]const u8 = null;
417 if (findKeySection(contents, &line_it) != null)
418 seed = findKeySection(contents, &line_it);
419 if (seed == null)
420 seed = findNkey(contents) orelse return error.NoNkeySeedFound;
421 if (!isValidCredsNkey(seed.?))
422 return error.NoNkeySeedFound;
423 return SeedKeyPair.fromTextSeed(seed.?[0..text_seed_len]) catch return error.NoNkeySeedFound;
424}
425
426pub fn parseDecoratedUserNkey(contents: []const u8) (NoNkeySeedFoundError || NoNkeyUserSeedFoundError)!SeedKeyPair {
427 var key = try parseDecoratedNkey(contents);
428 if (!mem.startsWith(u8, &key.seedText(), "SU")) return error.NoNkeyUserSeedFound;
429 defer key.wipe();
430 return key;
431}
432
433fn isValidCredsNkey(text: []const u8) bool {
434 const valid_prefix =
435 mem.startsWith(u8, text, "SO") or
436 mem.startsWith(u8, text, "SA") or
437 mem.startsWith(u8, text, "SU");
438 const valid_len = text.len >= text_seed_len;
439 return valid_prefix and valid_len;
440}
441
442fn findNkey(text: []const u8) ?[]const u8 {
443 var line_it = std.mem.split(text, "\n");
444 var current_off: usize = 0;
445 while (line_it.next()) |line| {
446 for (line) |c, i| {
447 if (!ascii.isSpace(c)) {
448 if (isValidCredsNkey(line[i..])) return line[i..];
449 break;
450 }
451 }
452 }
453 return null;
454}
455
456fn wipeKeyPair(kp: *Ed25519.KeyPair) void {
457 wipeBytes(&kp.public_key);
458 wipeBytes(&kp.secret_key);
459}
460
461fn wipeBytes(bs: []u8) void {
462 for (bs) |*b| b.* = 0;
463}
464
465test "reference all declarations" {
466 testing.refAllDecls(@This());
467 testing.refAllDecls(Role);
468 testing.refAllDecls(SeedKeyPair);
469 testing.refAllDecls(PublicKey);
470 testing.refAllDecls(PrivateKey);
471}
472
473test "key conversions" {
474 var key_pair = try SeedKeyPair.generate(.server);
475 var decoded_seed = try SeedKeyPair.fromTextSeed(&key_pair.seedText());
476 try testing.expect(isValidEncoding(&decoded_seed.seedText()));
477
478 var pub_key_str_a = key_pair.publicKeyText();
479 var priv_key_str_a = key_pair.privateKeyText();
480 try testing.expect(pub_key_str_a.len != 0);
481 try testing.expect(priv_key_str_a.len != 0);
482 try testing.expect(isValidEncoding(&pub_key_str_a));
483 try testing.expect(isValidEncoding(&priv_key_str_a));
484
485 var pub_key = key_pair.intoPublicKey();
486 var pub_key_str_b = pub_key.publicKeyText();
487 try testing.expectEqualStrings(&pub_key_str_a, &pub_key_str_b);
488
489 var priv_key = key_pair.intoPrivateKey();
490 var priv_key_str_b = priv_key.privateKeyText();
491 try testing.expectEqualStrings(&priv_key_str_a, &priv_key_str_b);
492}
493
494test "decode" {
495 const kp = try SeedKeyPair.generate(.account);
496 const seed_text = kp.seedText();
497 const pub_key_text = kp.publicKeyText();
498 const priv_key_text = kp.privateKeyText();
499
500 _ = try SeedKeyPair.fromTextSeed(&seed_text);
501 _ = try PublicKey.fromTextPublicKey(&pub_key_text);
502 _ = try PrivateKey.fromTextPrivateKey(&priv_key_text);
503
504 try testing.expectError(error.InvalidChecksum, PublicKey.fromTextPublicKey(seed_text[0..text_public_len]));
505 try testing.expectError(error.InvalidChecksum, SeedKeyPair.fromTextSeed(priv_key_text[0..text_seed_len]));
506}
507
508test "seed" {
509 inline for (@typeInfo(Role).Enum.fields) |field| {
510 const role = @field(Role, field.name);
511 const kp = try SeedKeyPair.generate(role);
512 const decoded = try SeedKeyPair.fromTextSeed(&kp.seedText());
513 if (decoded.role != role) {
514 std.debug.print("expected role {}, found role {}\n", .{ role, decoded.role });
515 return error.TestUnexpectedError;
516 }
517 }
518}
519
520test "public key" {
521 inline for (@typeInfo(Role).Enum.fields) |field| {
522 const role = @field(Role, field.name);
523 const kp = try SeedKeyPair.generate(role);
524 const decoded_pub_key = try PublicKey.fromTextPublicKey(&kp.publicKeyText());
525 if (decoded_pub_key.role != role) {
526 std.debug.print("expected role {}, found role {}\n", .{ role, decoded_pub_key.role });
527 return error.TestUnexpectedError;
528 }
529 }
530}
531
532test "different key types" {
533 inline for (@typeInfo(Role).Enum.fields) |field| {
534 const role = @field(Role, field.name);
535
536 const kp = try SeedKeyPair.generate(role);
537 _ = try SeedKeyPair.fromTextSeed(&kp.seedText());
538
539 const pub_key_str = kp.publicKeyText();
540 try testing.expect(pub_key_str[0] == role.letter());
541 try testing.expect(isValidPublicKey(&pub_key_str, role));
542
543 const priv_key_str = kp.privateKeyText();
544 try testing.expect(priv_key_str[0] == 'P');
545 try testing.expect(isValidPrivateKey(&priv_key_str));
546
547 const data = "Hello, world!";
548 const sig = try kp.sign(data);
549 try testing.expect(sig.len == Ed25519.signature_length);
550 try kp.verify(data, sig);
551 }
552}
553
554test "validation" {
555 const roles = @typeInfo(Role).Enum.fields;
556 inline for (roles) |field, i| {
557 const role = @field(Role, field.name);
558 const next_role = next: {
559 const next_field_i = if (i == roles.len - 1) 0 else i + 1;
560 std.debug.assert(next_field_i != i);
561 break :next @field(Role, roles[next_field_i].name);
562 };
563 const kp = try SeedKeyPair.generate(role);
564
565 const seed_str = kp.seedText();
566 const pub_key_str = kp.publicKeyText();
567 const priv_key_str = kp.privateKeyText();
568
569 try testing.expect(isValidSeed(&seed_str, role));
570 try testing.expect(isValidSeed(&seed_str, null));
571 try testing.expect(isValidPublicKey(&pub_key_str, null));
572 try testing.expect(isValidPublicKey(&pub_key_str, role));
573 try testing.expect(isValidPrivateKey(&priv_key_str));
574
575 try testing.expect(!isValidSeed(&seed_str, next_role));
576 try testing.expect(!isValidSeed(&pub_key_str, null));
577 try testing.expect(!isValidSeed(&priv_key_str, null));
578 try testing.expect(!isValidPublicKey(&pub_key_str, next_role));
579 try testing.expect(!isValidPublicKey(&seed_str, null));
580 try testing.expect(!isValidPublicKey(&priv_key_str, null));
581 try testing.expect(!isValidPrivateKey(&seed_str));
582 try testing.expect(!isValidPrivateKey(&pub_key_str));
583 }
584
585 try testing.expect(!isValidSeed("seed", null));
586 try testing.expect(!isValidPublicKey("public key", null));
587 try testing.expect(!isValidPrivateKey("private key"));
588}
589
590test "from seed" {
591 const kp = try SeedKeyPair.generate(.account);
592 const kp_from_raw = try SeedKeyPair.fromRawSeed(kp.role, kp.kp.secret_key[0..Ed25519.seed_length]);
593 try testing.expect(std.meta.eql(kp, kp_from_raw));
594
595 const data = "Hello, World!";
596 const sig = try kp.sign(data);
597
598 const seed = kp.seedText();
599 try testing.expect(mem.startsWith(u8, &seed, "SA"));
600
601 const kp2 = try SeedKeyPair.fromTextSeed(&seed);
602 try kp2.verify(data, sig);
603}
604
605test "from public key" {
606 const kp = try SeedKeyPair.generate(.user);
607
608 const pk_text = kp.publicKeyText();
609 const pk_text_clone = kp.publicKeyText();
610 try testing.expectEqualStrings(&pk_text, &pk_text_clone);
611
612 const pk = try PublicKey.fromTextPublicKey(&pk_text);
613 const pk_text_clone_2 = pk.publicKeyText();
614 try testing.expect(std.meta.eql(pk, kp.intoPublicKey()));
615 try testing.expect(std.meta.eql(pk, PublicKey.fromRawPublicKey(kp.role, &kp.kp.public_key)));
616 try testing.expectEqualStrings(&pk_text, &pk_text_clone_2);
617
618 const data = "Hello, world!";
619
620 const sig = try kp.sign(data);
621 try pk.verify(data, sig);
622
623 // Create another user to sign and make sure verification fails
624 const kp2 = try SeedKeyPair.generate(.user);
625 const sig2 = try kp2.sign(data);
626
627 try testing.expectError(error.InvalidSignature, pk.verify(data, sig2));
628}
629
630test "from private key" {
631 const kp = try SeedKeyPair.generate(.account);
632
633 const pk_text = kp.privateKeyText();
634 const pk_text_clone = kp.privateKeyText();
635 try testing.expectEqualStrings(&pk_text, &pk_text_clone);
636
637 const pk = try PrivateKey.fromTextPrivateKey(&pk_text);
638 const pk_text_clone_2 = pk.privateKeyText();
639 try testing.expect(std.meta.eql(pk, kp.intoPrivateKey()));
640 try testing.expect(std.meta.eql(kp, pk.intoSeedKeyPair(.account)));
641 try testing.expect(std.meta.eql(pk, PrivateKey.fromRawPrivateKey(&kp.kp.secret_key)));
642 try testing.expectEqualStrings(&pk_text, &pk_text_clone_2);
643
644 const data = "Hello, World!";
645
646 const sig0 = try kp.sign(data);
647 const sig1 = try pk.sign(data);
648 try testing.expectEqualSlices(u8, &sig0, &sig1);
649 try pk.verify(data, sig0);
650 try kp.verify(data, sig1);
651
652 const kp2 = try SeedKeyPair.generate(.account);
653 const sig2 = try kp2.sign(data);
654
655 try testing.expectError(error.InvalidSignature, pk.verify(data, sig2));
656}
657
658test "bad decode" {
659 const kp = try SeedKeyPair.fromTextSeed("SAAHPQF3GOP4IP5SHKHCNBOHD5TMGSW4QQL6RTZAPEEYOQ2NRBIAKCCLQA");
660
661 var bad_seed = kp.seedText();
662 bad_seed[1] = 'S';
663 try testing.expectError(error.InvalidChecksum, SeedKeyPair.fromTextSeed(&bad_seed));
664
665 var bad_pub_key = kp.publicKeyText();
666 bad_pub_key[bad_pub_key.len - 1] = 'O';
667 bad_pub_key[bad_pub_key.len - 2] = 'O';
668 try testing.expectError(error.InvalidChecksum, PublicKey.fromTextPublicKey(&bad_pub_key));
669
670 var bad_priv_key = kp.privateKeyText();
671 bad_priv_key[bad_priv_key.len - 1] = 'O';
672 bad_priv_key[bad_priv_key.len - 2] = 'O';
673 try testing.expectError(error.InvalidChecksum, PrivateKey.fromTextPrivateKey(&bad_priv_key));
674}
675
676test "wipe" {
677 const kp = try SeedKeyPair.generate(.account);
678 const pub_key = kp.intoPublicKey();
679 const priv_key = kp.intoPrivateKey();
680
681 var kp_clone = kp;
682 kp_clone.wipe();
683 try testing.expect(!std.meta.eql(kp_clone.kp, kp.kp));
684
685 var pub_key_clone = pub_key;
686 pub_key_clone.wipe();
687 try testing.expect(!std.meta.eql(pub_key_clone.key, pub_key.key));
688
689 var priv_key_clone = priv_key;
690 priv_key_clone.wipe();
691 try testing.expect(!std.meta.eql(priv_key_clone.kp, priv_key.kp));
692}
693
694test "parse decorated JWT (bad)" {
695 try testing.expectEqualStrings("foo", parseDecoratedJwt("foo"));
696}
697
698test "parse decorated seed (bad)" {
699 try testing.expectError(error.NoNkeySeedFound, parseDecoratedNkey("foo"));
700}
701
702test "parse decorated seed and JWT" {
703 const creds =
704 \\-----BEGIN NATS USER JWT-----
705 \\eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJUWEg1TUxDNTdPTUJUQURYNUJNU0RLWkhSQUtXUFM0TkdHRFFPVlJXRzUyRFdaUlFFVERBIiwiaWF0IjoxNjIxNTgyOTU1LCJpc3MiOiJBQ1ZUQVZMQlFKTklQRjdNWFZWSlpZUFhaTkdFQUZMWVpTUjJSNVRZNk9ESjNSTTRYV0FDNUVFRiIsIm5hbWUiOiJ0ZXN0Iiwic3ViIjoiVUJHSlhLRkVWUlFEM05LM0lDRVc1Q0lDSzM1NkdESVZORkhaRUU0SzdMMkRYWTdORVNQVlFVNEwiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e30sInN1YnMiOi0xLCJkYXRhIjotMSwicGF5bG9hZCI6LTEsInR5cGUiOiJ1c2VyIiwidmVyc2lvbiI6Mn19.OhPLDZflyJ_keg2xBRDHZZhG5x_Qf_Yb61k9eHLs9zLRf0_ETwMd0PNZI_isuBhXYevobXHVoYA3oxvMVGlDCQ
706 \\------END NATS USER JWT------
707 \\
708 \\************************* IMPORTANT *************************
709 \\NKEY Seed printed below can be used to sign and prove identity.
710 \\NKEYs are sensitive and should be treated as secrets.
711 \\
712 \\-----BEGIN USER NKEY SEED-----
713 \\SUAGIEYODKBBTUMOB666Z5KA4FCWAZV7HWSGRHOD7MK6UM5IYLWLACH7DQ
714 \\------END USER NKEY SEED------
715 \\
716 \\*************************************************************
717 ;
718 const jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiJUWEg1TUxDNTdPTUJUQURYNUJNU0RLWkhSQUtXUFM0TkdHRFFPVlJXRzUyRFdaUlFFVERBIiwiaWF0IjoxNjIxNTgyOTU1LCJpc3MiOiJBQ1ZUQVZMQlFKTklQRjdNWFZWSlpZUFhaTkdFQUZMWVpTUjJSNVRZNk9ESjNSTTRYV0FDNUVFRiIsIm5hbWUiOiJ0ZXN0Iiwic3ViIjoiVUJHSlhLRkVWUlFEM05LM0lDRVc1Q0lDSzM1NkdESVZORkhaRUU0SzdMMkRYWTdORVNQVlFVNEwiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e30sInN1YnMiOi0xLCJkYXRhIjotMSwicGF5bG9hZCI6LTEsInR5cGUiOiJ1c2VyIiwidmVyc2lvbiI6Mn19.OhPLDZflyJ_keg2xBRDHZZhG5x_Qf_Yb61k9eHLs9zLRf0_ETwMd0PNZI_isuBhXYevobXHVoYA3oxvMVGlDCQ";
719 const seed = "SUAGIEYODKBBTUMOB666Z5KA4FCWAZV7HWSGRHOD7MK6UM5IYLWLACH7DQ";
720
721 var got_kp = try parseDecoratedUserNkey(creds);
722 try testing.expectEqualStrings(seed, &got_kp.seedText());
723
724 got_kp = try parseDecoratedNkey(creds);
725 try testing.expectEqualStrings(seed, &got_kp.seedText());
726
727 var got_jwt = parseDecoratedJwt(creds);
728 try testing.expectEqualStrings(jwt, got_jwt);
729}