Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / apple / FindFamily / FindFamilyiOS / Crypto / MLDSA65.swift
MLDSA65.swift297 lines · 9.5 KiBRaw
| 1 | import Foundation |
| 2 | |
| 3 | // ML-DSA-65 (FIPS 204) key generation, matching the `fips204` Rust crate used by |
| 4 | // Android's `libe2ee_pqc.so`. |
| 5 | // |
| 6 | // Only KeyGen is implemented: a device's public identity bundle is |
| 7 | // [kemPub ‖ dsaPub], so the ML-DSA half has to be a real, correctly-encoded key |
| 8 | // even though FindFamily itself never signs or verifies with it (the signature |
| 9 | // half exists for Office's roster authentication and is carried here for format |
| 10 | // compatibility). If signing is ever needed on iOS, Sign/Verify go here. |
| 11 | // |
| 12 | // Parameter set ML-DSA-65: q=8380417, n=256, k=6, l=5, eta=4, d=13. |
| 13 | |
| 14 | enum MLDSAError: Error { |
| 15 | case badLength(String) |
| 16 | } |
| 17 | |
| 18 | enum MLDSA65 { |
| 19 | // MARK: - Parameters |
| 20 | |
| 21 | static let n = 256 |
| 22 | static let q: Int32 = 8_380_417 |
| 23 | static let k = 6 |
| 24 | static let l = 5 |
| 25 | static let eta: Int32 = 4 |
| 26 | static let d = 13 |
| 27 | |
| 28 | /// 32 + 32*k*(bitlen(q-1) - d) = 32 + 32*6*10. |
| 29 | static let publicKeyLength = 1952 |
| 30 | /// 128 + 32*(l*4 + k*4 + k*13). |
| 31 | static let privateKeyLength = 4032 |
| 32 | static let seedLength = 32 |
| 33 | |
| 34 | // MARK: - Modular arithmetic |
| 35 | |
| 36 | @inline(__always) private static func addMod(_ a: Int32, _ b: Int32) -> Int32 { |
| 37 | let s = a + b |
| 38 | return s >= q ? s - q : s |
| 39 | } |
| 40 | |
| 41 | @inline(__always) private static func subMod(_ a: Int32, _ b: Int32) -> Int32 { |
| 42 | let s = a - b |
| 43 | return s < 0 ? s + q : s |
| 44 | } |
| 45 | |
| 46 | @inline(__always) private static func mulMod(_ a: Int32, _ b: Int32) -> Int32 { |
| 47 | Int32((Int(a) * Int(b)) % Int(q)) |
| 48 | } |
| 49 | |
| 50 | private static func powMod(_ base: Int32, _ exp: Int) -> Int32 { |
| 51 | var result: Int32 = 1 |
| 52 | var b = base |
| 53 | var e = exp |
| 54 | while e > 0 { |
| 55 | if e & 1 == 1 { result = mulMod(result, b) } |
| 56 | b = mulMod(b, b) |
| 57 | e >>= 1 |
| 58 | } |
| 59 | return result |
| 60 | } |
| 61 | |
| 62 | /// Reverses 8 bits. |
| 63 | private static func bitRev8(_ x: Int) -> Int { |
| 64 | var r = 0 |
| 65 | for i in 0..<8 where (x >> i) & 1 == 1 { r |= 1 << (7 - i) } |
| 66 | return r |
| 67 | } |
| 68 | |
| 69 | /// zetas[i] = 1753^BitRev8(i) mod q. |
| 70 | private static let zetas: [Int32] = (0..<256).map { powMod(1753, bitRev8($0)) } |
| 71 | |
| 72 | // MARK: - NTT (full 256-point, so multiplication is plain pointwise) |
| 73 | |
| 74 | /// FIPS 204 Algorithm 41. |
| 75 | static func ntt(_ w: inout [Int32]) { |
| 76 | var i = 0 |
| 77 | var len = 128 |
| 78 | while len >= 1 { |
| 79 | var start = 0 |
| 80 | while start < n { |
| 81 | i += 1 |
| 82 | let z = zetas[i] |
| 83 | for j in start..<(start + len) { |
| 84 | let t = mulMod(z, w[j + len]) |
| 85 | w[j + len] = subMod(w[j], t) |
| 86 | w[j] = addMod(w[j], t) |
| 87 | } |
| 88 | start += 2 * len |
| 89 | } |
| 90 | len /= 2 |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// FIPS 204 Algorithm 42. |
| 95 | static func inverseNTT(_ w: inout [Int32]) { |
| 96 | var i = 256 |
| 97 | var len = 1 |
| 98 | while len < n { |
| 99 | var start = 0 |
| 100 | while start < n { |
| 101 | i -= 1 |
| 102 | let z = q - zetas[i] // -zeta^BitRev8(i) |
| 103 | for j in start..<(start + len) { |
| 104 | let t = w[j] |
| 105 | w[j] = addMod(t, w[j + len]) |
| 106 | w[j + len] = mulMod(z, subMod(t, w[j + len])) |
| 107 | } |
| 108 | start += 2 * len |
| 109 | } |
| 110 | len *= 2 |
| 111 | } |
| 112 | // 256^-1 mod q |
| 113 | for j in 0..<n { w[j] = mulMod(w[j], 8_347_681) } |
| 114 | } |
| 115 | |
| 116 | // MARK: - Sampling |
| 117 | |
| 118 | /// FIPS 204 Algorithm 30: rejection sampling of a uniform polynomial in NTT form. |
| 119 | private static func rejNTTPoly(_ seed: [UInt8]) -> [Int32] { |
| 120 | var xof = Keccak.shake128Reader(seed) |
| 121 | var a = [Int32](repeating: 0, count: n) |
| 122 | var j = 0 |
| 123 | while j < n { |
| 124 | let b = xof.squeeze(3) |
| 125 | let z = Int32(b[0]) | (Int32(b[1]) << 8) | (Int32(b[2] & 0x7F) << 16) |
| 126 | if z < q { |
| 127 | a[j] = z |
| 128 | j += 1 |
| 129 | } |
| 130 | } |
| 131 | return a |
| 132 | } |
| 133 | |
| 134 | /// FIPS 204 Algorithm 31 with eta = 4: coefficients in [-4, 4]. |
| 135 | private static func rejBoundedPoly(_ seed: [UInt8]) -> [Int32] { |
| 136 | var xof = Keccak.shake256Reader(seed) |
| 137 | var a = [Int32](repeating: 0, count: n) |
| 138 | var j = 0 |
| 139 | // CoeffFromHalfByte for eta=4: b < 9 -> 4 - b, else reject. |
| 140 | while j < n { |
| 141 | let z = xof.squeeze(1)[0] |
| 142 | let lo = Int32(z & 0x0F) |
| 143 | let hi = Int32(z >> 4) |
| 144 | if lo < 9 { |
| 145 | a[j] = 4 - lo |
| 146 | j += 1 |
| 147 | } |
| 148 | if hi < 9 && j < n { |
| 149 | a[j] = 4 - hi |
| 150 | j += 1 |
| 151 | } |
| 152 | } |
| 153 | return a |
| 154 | } |
| 155 | |
| 156 | /// FIPS 204 Algorithm 32. Note the index order: Â[r,s] from ρ‖s‖r. |
| 157 | private static func expandA(_ rho: [UInt8]) -> [[[Int32]]] { |
| 158 | var a = [[[Int32]]]() |
| 159 | a.reserveCapacity(k) |
| 160 | for r in 0..<k { |
| 161 | var row = [[Int32]]() |
| 162 | row.reserveCapacity(l) |
| 163 | for s in 0..<l { |
| 164 | row.append(rejNTTPoly(rho + [UInt8(s), UInt8(r)])) |
| 165 | } |
| 166 | a.append(row) |
| 167 | } |
| 168 | return a |
| 169 | } |
| 170 | |
| 171 | /// FIPS 204 Algorithm 33. |
| 172 | private static func expandS(_ rhoPrime: [UInt8]) -> (s1: [[Int32]], s2: [[Int32]]) { |
| 173 | var s1 = [[Int32]]() |
| 174 | for r in 0..<l { |
| 175 | s1.append(rejBoundedPoly(rhoPrime + [UInt8(r & 0xFF), UInt8((r >> 8) & 0xFF)])) |
| 176 | } |
| 177 | var s2 = [[Int32]]() |
| 178 | for r in 0..<k { |
| 179 | let idx = r + l |
| 180 | s2.append(rejBoundedPoly(rhoPrime + [UInt8(idx & 0xFF), UInt8((idx >> 8) & 0xFF)])) |
| 181 | } |
| 182 | return (s1, s2) |
| 183 | } |
| 184 | |
| 185 | // MARK: - Rounding |
| 186 | |
| 187 | /// FIPS 204 Algorithm 35: r -> (r1, r0) with r = r1*2^d + r0, r0 centered. |
| 188 | private static func power2Round(_ r: Int32) -> (r1: Int32, r0: Int32) { |
| 189 | let rPlus = r % q |
| 190 | var r0 = rPlus & ((1 << Int32(d)) - 1) |
| 191 | if r0 > (1 << Int32(d - 1)) { r0 -= (1 << Int32(d)) } |
| 192 | let r1 = (rPlus - r0) >> Int32(d) |
| 193 | return (r1, r0) |
| 194 | } |
| 195 | |
| 196 | // MARK: - Bit packing |
| 197 | |
| 198 | /// FIPS 204 Algorithm 16: pack coefficients directly in `bits` bits each. |
| 199 | private static func simpleBitPack(_ w: [Int32], bits: Int) -> [UInt8] { |
| 200 | packLSBFirst(w.map { UInt32(bitPattern: $0) }, bits: bits) |
| 201 | } |
| 202 | |
| 203 | /// FIPS 204 Algorithm 17: pack (b - w[i]) in `bits` bits each. |
| 204 | private static func bitPack(_ w: [Int32], b: Int32, bits: Int) -> [UInt8] { |
| 205 | packLSBFirst(w.map { UInt32(bitPattern: b - $0) }, bits: bits) |
| 206 | } |
| 207 | |
| 208 | private static func packLSBFirst(_ values: [UInt32], bits: Int) -> [UInt8] { |
| 209 | var out = [UInt8](repeating: 0, count: (values.count * bits + 7) / 8) |
| 210 | var acc: UInt64 = 0 |
| 211 | var accBits = 0 |
| 212 | var pos = 0 |
| 213 | for v in values { |
| 214 | acc |= UInt64(v & ((1 << UInt32(bits)) - 1)) << UInt64(accBits) |
| 215 | accBits += bits |
| 216 | while accBits >= 8 { |
| 217 | out[pos] = UInt8(acc & 0xFF) |
| 218 | pos += 1 |
| 219 | acc >>= 8 |
| 220 | accBits -= 8 |
| 221 | } |
| 222 | } |
| 223 | if accBits > 0 { out[pos] = UInt8(acc & 0xFF) } |
| 224 | return out |
| 225 | } |
| 226 | |
| 227 | // MARK: - KeyGen |
| 228 | |
| 229 | /// FIPS 204 Algorithm 6 (KeyGen_internal). Returns the raw FIPS-encoded key pair. |
| 230 | static func keyGen(seed xi: [UInt8]) throws -> (publicKey: [UInt8], privateKey: [UInt8]) { |
| 231 | guard xi.count == seedLength else { |
| 232 | throw MLDSAError.badLength("ML-DSA seed must be \(seedLength) bytes, got \(xi.count)") |
| 233 | } |
| 234 | // (rho, rho', K) <- H(xi ‖ k ‖ l, 128) |
| 235 | let h = Keccak.shake256(xi + [UInt8(k), UInt8(l)], outputCount: 128) |
| 236 | let rho = Array(h[0..<32]) |
| 237 | let rhoPrime = Array(h[32..<96]) |
| 238 | let bigK = Array(h[96..<128]) |
| 239 | |
| 240 | let aHat = expandA(rho) |
| 241 | let (s1, s2) = expandS(rhoPrime) |
| 242 | |
| 243 | // t = NTT^-1(Â ∘ NTT(s1)) + s2 |
| 244 | var s1Hat = s1.map { poly -> [Int32] in |
| 245 | var p = poly.map { $0 < 0 ? $0 + q : $0 } |
| 246 | ntt(&p) |
| 247 | return p |
| 248 | } |
| 249 | var t = [[Int32]]() |
| 250 | for r in 0..<k { |
| 251 | var acc = [Int32](repeating: 0, count: n) |
| 252 | for s in 0..<l { |
| 253 | for i in 0..<n { |
| 254 | acc[i] = addMod(acc[i], mulMod(aHat[r][s][i], s1Hat[s][i])) |
| 255 | } |
| 256 | } |
| 257 | inverseNTT(&acc) |
| 258 | for i in 0..<n { |
| 259 | let s2c = s2[r][i] < 0 ? s2[r][i] + q : s2[r][i] |
| 260 | acc[i] = addMod(acc[i], s2c) |
| 261 | } |
| 262 | t.append(acc) |
| 263 | } |
| 264 | s1Hat.removeAll() |
| 265 | |
| 266 | // (t1, t0) = Power2Round(t) |
| 267 | var t1 = [[Int32]]() |
| 268 | var t0 = [[Int32]]() |
| 269 | for r in 0..<k { |
| 270 | var hi = [Int32](repeating: 0, count: n) |
| 271 | var lo = [Int32](repeating: 0, count: n) |
| 272 | for i in 0..<n { |
| 273 | let (a, b) = power2Round(t[r][i]) |
| 274 | hi[i] = a |
| 275 | lo[i] = b |
| 276 | } |
| 277 | t1.append(hi) |
| 278 | t0.append(lo) |
| 279 | } |
| 280 | |
| 281 | // pkEncode: rho ‖ SimpleBitPack(t1[i], 10 bits) |
| 282 | var pk = rho |
| 283 | for r in 0..<k { pk += simpleBitPack(t1[r], bits: 10) } |
| 284 | |
| 285 | // skEncode: rho ‖ K ‖ tr ‖ BitPack(s1, eta) ‖ BitPack(s2, eta) ‖ BitPack(t0, 2^(d-1)) |
| 286 | let tr = Keccak.shake256(pk, outputCount: 64) |
| 287 | var sk = rho + bigK + tr |
| 288 | for r in 0..<l { sk += bitPack(s1[r], b: eta, bits: 4) } |
| 289 | for r in 0..<k { sk += bitPack(s2[r], b: eta, bits: 4) } |
| 290 | for r in 0..<k { sk += bitPack(t0[r], b: 1 << Int32(d - 1), bits: d) } |
| 291 | |
| 292 | guard pk.count == publicKeyLength, sk.count == privateKeyLength else { |
| 293 | throw MLDSAError.badLength("ML-DSA encode produced pk=\(pk.count) sk=\(sk.count)") |
| 294 | } |
| 295 | return (pk, sk) |
| 296 | } |
| 297 | } |