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
//! The shared secret a syncer and a repo host MAC a response with, from the
//! secret export of HPKE (RFC 9180 §6.2) in base mode with the
//! DHKEM(P-256, HKDF-SHA256) / HKDF-SHA256 / export-only suite. Nothing is
//! encrypted. Mirrors `@atproto/space` `kem.ts`.
const std = @import("std");
const multicodec = @import("../crypto/multicodec.zig");
const P256 = std.crypto.ecc.P256;
const HkdfSha256 = std.crypto.kdf.hkdf.HkdfSha256;
pub const Error = error{ InvalidKemKey, OutOfMemory };
pub const Encapsulation = struct {
/// HPKE's `enc`: the syncer's ephemeral P-256 public key as a did:key, sent
/// as the `keyid` of its MAC request.
key_share: []u8,
shared_secret: [32]u8,
};
/// Syncer side: a fresh ephemeral key share against the author's
/// `#atproto_kem` key. Use a new one for every request.
pub fn encapsulate(io: std.Io, allocator: std.mem.Allocator, author_kem_key: []const u8) Error!Encapsulation {
const author = try p256Point(allocator, author_kem_key);
const ephemeral = std.crypto.sign.ecdsa.EcdsaP256Sha256.KeyPair.generate(io);
const point = ephemeral.public_key.p;
const dh = (author.mul(ephemeral.secret_key.toBytes(), .big) catch return error.InvalidKemKey).affineCoordinates().x.toBytes(.big);
return .{
.key_share = multicodec.formatDidKey(allocator, .p256, &point.toCompressedSec1()) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidKemKey,
},
.shared_secret = deriveSharedSecret(&dh, &point.toUncompressedSec1(), &author.toUncompressedSec1()),
};
}
/// Repo host side: the same secret from the syncer's `key_share` and the
/// author's KEM secret key.
pub fn decapsulate(author_secret: [32]u8, key_share: []const u8) Error![32]u8 {
var buf: [4096]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buf);
const enc = try p256Point(fba.allocator(), key_share);
const author = P256.basePoint.mul(author_secret, .big) catch return error.InvalidKemKey;
const dh = (enc.mul(author_secret, .big) catch return error.InvalidKemKey).affineCoordinates().x.toBytes(.big);
return deriveSharedSecret(&dh, &enc.toUncompressedSec1(), &author.toUncompressedSec1());
}
const version = "HPKE-v1";
/// DHKEM(P-256, HKDF-SHA256).
const kem_id = "KEM\x00\x10";
/// That KEM, HKDF-SHA256, and the export-only AEAD.
const suite_id = "HPKE\x00\x10\x00\x01\xff\xff";
/// Ties the secret to this protocol.
const info = "atproto-mac";
fn labeledExtract(comptime id: []const u8, salt: []const u8, comptime label: []const u8, ikm: []const u8) [HkdfSha256.prk_length]u8 {
var extract = HkdfSha256.extractInit(salt);
extract.update(version ++ id ++ label);
extract.update(ikm);
var prk: [HkdfSha256.prk_length]u8 = undefined;
extract.final(&prk);
return prk;
}
fn labeledExpand(comptime id: []const u8, prk: [HkdfSha256.prk_length]u8, comptime label: []const u8, comptime info_len: usize, label_info: [info_len]u8) [32]u8 {
const prefix = "\x00\x20" ++ version ++ id ++ label;
var labeled: [prefix.len + info_len]u8 = undefined;
@memcpy(labeled[0..prefix.len], prefix);
@memcpy(labeled[prefix.len..], &label_info);
var out: [32]u8 = undefined;
HkdfSha256.expand(&out, &labeled, prk);
return out;
}
/// SetupBaseS (or SetupBaseR), then an export with an empty exporter context.
fn deriveSharedSecret(dh: *const [32]u8, enc: *const [65]u8, author_key: *const [65]u8) [32]u8 {
const eae_prk = labeledExtract(kem_id, "", "eae_prk", dh);
const kem_secret = labeledExpand(kem_id, eae_prk, "shared_secret", 130, enc.* ++ author_key.*);
const psk_id_hash = labeledExtract(suite_id, "", "psk_id_hash", "");
const info_hash = labeledExtract(suite_id, "", "info_hash", info);
const context = [_]u8{0x00} ++ psk_id_hash ++ info_hash;
const secret = labeledExtract(suite_id, &kem_secret, "secret", "");
const exporter_secret = labeledExpand(suite_id, secret, "exp", context.len, context);
return labeledExpand(suite_id, exporter_secret, "sec", 0, .{});
}
fn p256Point(allocator: std.mem.Allocator, did_key: []const u8) Error!P256 {
const parsed = multicodec.parseDidKey(allocator, did_key) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.InvalidKemKey,
};
defer allocator.free(parsed.raw);
if (parsed.key_type != .p256) return error.InvalidKemKey;
return P256.fromSec1(parsed.raw) catch error.InvalidKemKey;
}
test "matches the HPKE secret export vector" {
// The export-only DHKEM(P-256, HKDF-SHA256) HPKE vector's `enc` and `skRm`,
// with the secret the reference SDK's tests computed using Go's crypto/hpke,
// info "atproto-mac" and an empty exporter context.
var enc: [65]u8 = undefined;
_ = try std.fmt.hexToBytes(&enc, "04d804370b7e24b94749eb1dc8df6d4d4a5d75f9effad01739ebcad5c54a40d57aaa8b4190fc124dbde2e4f1e1d1b012a3bc4038157dc29b55533a932306d8d38d");
var secret: [32]u8 = undefined;
_ = try std.fmt.hexToBytes(&secret, "62c3868357a464f8461d03aa0182c7cebcde841036aea7230ddc7339f1088346");
const point = try P256.fromSec1(&enc);
const key_share = try multicodec.formatDidKey(std.testing.allocator, .p256, &point.toCompressedSec1());
defer std.testing.allocator.free(key_share);
try std.testing.expectEqualStrings(
"2060e0558d1b34c10086bc137f849bb79ba59fcdc30544418e35c9cd301f0d0d",
&std.fmt.bytesToHex(try decapsulate(secret, key_share), .lower),
);
}
test "both sides derive the same secret, and another author key does not" {
const io = std.testing.io;
const a = std.testing.allocator;
const author: [32]u8 = @splat(0x24);
const other: [32]u8 = @splat(0x25);
const author_did = try multicodec.formatDidKey(a, .p256, &(try P256.basePoint.mul(author, .big)).toCompressedSec1());
defer a.free(author_did);
const first = try encapsulate(io, a, author_did);
defer a.free(first.key_share);
const second = try encapsulate(io, a, author_did);
defer a.free(second.key_share);
try std.testing.expectEqual(first.shared_secret, try decapsulate(author, first.key_share));
try std.testing.expect(!std.mem.eql(u8, &first.shared_secret, &second.shared_secret));
try std.testing.expect(!std.mem.eql(u8, &first.shared_secret, &try decapsulate(other, first.key_share)));
}
test "refuses keys that are not P-256" {
const a = std.testing.allocator;
const k256 = try multicodec.formatDidKey(a, .secp256k1, &(try std.crypto.ecc.Secp256k1.basePoint.mul(@splat(0x24), .big)).toCompressedSec1());
defer a.free(k256);
try std.testing.expectError(error.InvalidKemKey, decapsulate(@splat(0x24), k256));
try std.testing.expectError(error.InvalidKemKey, decapsulate(@splat(0x24), "did:key:nope"));
try std.testing.expectError(error.InvalidKemKey, encapsulate(std.testing.io, a, k256));
}