| 1 | const std = @import("std"); |
| 2 | const crypto = std.crypto; |
| 3 | const debug = std.debug; |
| 4 | const fmt = std.fmt; |
| 5 | const mem = std.mem; |
| 6 | |
| 7 | const Sha512 = crypto.hash.sha2.Sha512; |
| 8 | |
| 9 | const EncodingError = crypto.errors.EncodingError; |
| 10 | const IdentityElementError = crypto.errors.IdentityElementError; |
| 11 | const NonCanonicalError = crypto.errors.NonCanonicalError; |
| 12 | const SignatureVerificationError = crypto.errors.SignatureVerificationError; |
| 13 | const KeyMismatchError = crypto.errors.KeyMismatchError; |
| 14 | const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; |
| 15 | |
| 16 | /// Ed25519 (EdDSA) signatures. |
| 17 | pub const Ed25519 = struct { |
| 18 | /// The underlying elliptic curve. |
| 19 | pub const Curve = std.crypto.ecc.Edwards25519; |
| 20 | |
| 21 | /// Length (in bytes) of optional random bytes, for non-deterministic signatures. |
| 22 | pub const noise_length = 32; |
| 23 | |
| 24 | const CompressedScalar = Curve.scalar.CompressedScalar; |
| 25 | const Scalar = Curve.scalar.Scalar; |
| 26 | |
| 27 | /// An Ed25519 secret key. |
| 28 | pub const SecretKey = struct { |
| 29 | /// Length (in bytes) of a raw secret key. |
| 30 | pub const encoded_length = 64; |
| 31 | |
| 32 | bytes: [encoded_length]u8, |
| 33 | |
| 34 | /// Return the seed used to generate this secret key. |
| 35 | pub fn seed(self: SecretKey) [KeyPair.seed_length]u8 { |
| 36 | return self.bytes[0..KeyPair.seed_length].*; |
| 37 | } |
| 38 | |
| 39 | /// Return the raw public key bytes corresponding to this secret key. |
| 40 | pub fn publicKeyBytes(self: SecretKey) [PublicKey.encoded_length]u8 { |
| 41 | return self.bytes[KeyPair.seed_length..].*; |
| 42 | } |
| 43 | |
| 44 | /// Create a secret key from raw bytes. |
| 45 | pub fn fromBytes(bytes: [encoded_length]u8) !SecretKey { |
| 46 | return SecretKey{ .bytes = bytes }; |
| 47 | } |
| 48 | |
| 49 | /// Return the secret key as raw bytes. |
| 50 | pub fn toBytes(sk: SecretKey) [encoded_length]u8 { |
| 51 | return sk.bytes; |
| 52 | } |
| 53 | |
| 54 | // Return the clamped secret scalar and prefix for this secret key |
| 55 | fn scalarAndPrefix(self: SecretKey) struct { scalar: CompressedScalar, prefix: [32]u8 } { |
| 56 | var az: [Sha512.digest_length]u8 = undefined; |
| 57 | var h = Sha512.init(.{}); |
| 58 | h.update(&self.seed()); |
| 59 | h.final(&az); |
| 60 | |
| 61 | var s = az[0..32].*; |
| 62 | Curve.scalar.clamp(&s); |
| 63 | |
| 64 | return .{ .scalar = s, .prefix = az[32..].* }; |
| 65 | } |
| 66 | }; |
| 67 | |
| 68 | /// A Signer is used to incrementally compute a signature. |
| 69 | /// It can be obtained from a `KeyPair`, using the `signer()` function. |
| 70 | pub const Signer = struct { |
| 71 | h: Sha512, |
| 72 | scalar: CompressedScalar, |
| 73 | nonce: CompressedScalar, |
| 74 | r_bytes: [Curve.encoded_length]u8, |
| 75 | |
| 76 | fn init(scalar: CompressedScalar, nonce: CompressedScalar, public_key: PublicKey) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signer { |
| 77 | const r = try Curve.basePoint.mul(nonce); |
| 78 | const r_bytes = r.toBytes(); |
| 79 | |
| 80 | var t: [64]u8 = undefined; |
| 81 | t[0..32].* = r_bytes; |
| 82 | t[32..].* = public_key.bytes; |
| 83 | var h = Sha512.init(.{}); |
| 84 | h.update(&t); |
| 85 | |
| 86 | return Signer{ .h = h, .scalar = scalar, .nonce = nonce, .r_bytes = r_bytes }; |
| 87 | } |
| 88 | |
| 89 | /// Add new data to the message being signed. |
| 90 | pub fn update(self: *Signer, data: []const u8) void { |
| 91 | self.h.update(data); |
| 92 | } |
| 93 | |
| 94 | /// Compute a signature over the entire message. |
| 95 | pub fn finalize(self: *Signer) Signature { |
| 96 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 97 | self.h.final(&hram64); |
| 98 | const hram = Curve.scalar.reduce64(hram64); |
| 99 | |
| 100 | const s = Curve.scalar.mulAdd(hram, self.scalar, self.nonce); |
| 101 | |
| 102 | return Signature{ .r = self.r_bytes, .s = s }; |
| 103 | } |
| 104 | }; |
| 105 | |
| 106 | /// An Ed25519 public key. |
| 107 | pub const PublicKey = struct { |
| 108 | /// Length (in bytes) of a raw public key. |
| 109 | pub const encoded_length = 32; |
| 110 | |
| 111 | bytes: [encoded_length]u8, |
| 112 | |
| 113 | /// Create a public key from raw bytes. |
| 114 | pub fn fromBytes(bytes: [encoded_length]u8) NonCanonicalError!PublicKey { |
| 115 | try Curve.rejectNonCanonical(bytes); |
| 116 | return PublicKey{ .bytes = bytes }; |
| 117 | } |
| 118 | |
| 119 | /// Convert a public key to raw bytes. |
| 120 | pub fn toBytes(pk: PublicKey) [encoded_length]u8 { |
| 121 | return pk.bytes; |
| 122 | } |
| 123 | |
| 124 | fn signWithNonce(public_key: PublicKey, msg: []const u8, scalar: CompressedScalar, nonce: CompressedScalar) (IdentityElementError || NonCanonicalError || KeyMismatchError || WeakPublicKeyError)!Signature { |
| 125 | var st = try Signer.init(scalar, nonce, public_key); |
| 126 | st.update(msg); |
| 127 | return st.finalize(); |
| 128 | } |
| 129 | |
| 130 | fn computeNonceAndSign(public_key: PublicKey, msg: []const u8, noise: ?[noise_length]u8, scalar: CompressedScalar, prefix: []const u8) (IdentityElementError || NonCanonicalError || KeyMismatchError || WeakPublicKeyError)!Signature { |
| 131 | var h = Sha512.init(.{}); |
| 132 | if (noise) |*z| { |
| 133 | h.update(z); |
| 134 | } |
| 135 | h.update(prefix); |
| 136 | h.update(msg); |
| 137 | var nonce64: [64]u8 = undefined; |
| 138 | h.final(&nonce64); |
| 139 | |
| 140 | const nonce = Curve.scalar.reduce64(nonce64); |
| 141 | |
| 142 | return public_key.signWithNonce(msg, scalar, nonce); |
| 143 | } |
| 144 | }; |
| 145 | |
| 146 | /// A Verifier is used to incrementally verify a signature. |
| 147 | /// It can be obtained from a `Signature`, using the `verifier()` function. |
| 148 | pub const Verifier = struct { |
| 149 | h: Sha512, |
| 150 | s: CompressedScalar, |
| 151 | a: Curve, |
| 152 | expected_r: Curve, |
| 153 | |
| 154 | pub const InitError = NonCanonicalError || EncodingError || IdentityElementError; |
| 155 | |
| 156 | fn init(sig: Signature, public_key: PublicKey) InitError!Verifier { |
| 157 | const r = sig.r; |
| 158 | const s = sig.s; |
| 159 | try Curve.scalar.rejectNonCanonical(s); |
| 160 | const a = try Curve.fromBytes(public_key.bytes); |
| 161 | try a.rejectIdentity(); |
| 162 | try Curve.rejectNonCanonical(r); |
| 163 | const expected_r = try Curve.fromBytes(r); |
| 164 | try expected_r.rejectIdentity(); |
| 165 | |
| 166 | var h = Sha512.init(.{}); |
| 167 | h.update(&r); |
| 168 | h.update(&public_key.bytes); |
| 169 | |
| 170 | return Verifier{ .h = h, .s = s, .a = a, .expected_r = expected_r }; |
| 171 | } |
| 172 | |
| 173 | /// Add new content to the message to be verified. |
| 174 | pub fn update(self: *Verifier, msg: []const u8) void { |
| 175 | self.h.update(msg); |
| 176 | } |
| 177 | |
| 178 | fn isIdentity(p: Curve) bool { |
| 179 | return p.x.isZero() and p.y.equivalent(p.z); |
| 180 | } |
| 181 | |
| 182 | pub const VerifyError = WeakPublicKeyError || IdentityElementError || |
| 183 | SignatureVerificationError; |
| 184 | |
| 185 | /// Verify that the signature is valid for the entire message. |
| 186 | /// |
| 187 | /// This function uses cofactored verification for broad interoperability. |
| 188 | /// It aligns single-signature verification with common batch verification approaches. |
| 189 | /// |
| 190 | /// Return IdentityElement or NonCanonical if the public key or signature are not in the expected range, |
| 191 | /// or SignatureVerificationError if the signature is invalid for the given message and key. |
| 192 | pub fn verify(self: *Verifier) VerifyError!void { |
| 193 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 194 | self.h.final(&hram64); |
| 195 | const hram = Curve.scalar.reduce64(hram64); |
| 196 | const sb_ah = (try Curve.basePoint.mulDoubleBasePublic( |
| 197 | Curve.scalar.mul8(self.s), |
| 198 | self.a.clearCofactor().neg(), |
| 199 | hram, |
| 200 | )); |
| 201 | const check = sb_ah.sub(self.expected_r.clearCofactor()); |
| 202 | if (!isIdentity(check)) { |
| 203 | return error.SignatureVerificationFailed; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | /// Verify that the signature is valid for the entire message using cofactorless verification. |
| 208 | /// |
| 209 | /// This function performs strict verification without cofactor multiplication, |
| 210 | /// checking the exact equation: [s]B = R + [H(R,A,m)]A |
| 211 | /// |
| 212 | /// This is more restrictive than the cofactored `verify()` method and may reject |
| 213 | /// specially crafted signatures that would be accepted by cofactored verification. |
| 214 | /// But it will never reject valid signatures created using the `sign()` method. |
| 215 | /// |
| 216 | /// Return IdentityElement or NonCanonical if the public key or signature are not in the expected range, |
| 217 | /// or SignatureVerificationError if the signature is invalid for the given message and key. |
| 218 | pub fn verifyStrict(self: *Verifier) VerifyError!void { |
| 219 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 220 | self.h.final(&hram64); |
| 221 | const hram = Curve.scalar.reduce64(hram64); |
| 222 | const sb_ah = (try Curve.basePoint.mulDoubleBasePublic( |
| 223 | self.s, |
| 224 | self.a.neg(), |
| 225 | hram, |
| 226 | )); |
| 227 | const check = sb_ah.sub(self.expected_r); |
| 228 | if (!isIdentity(check)) { |
| 229 | return error.SignatureVerificationFailed; |
| 230 | } |
| 231 | } |
| 232 | }; |
| 233 | |
| 234 | /// An Ed25519 signature. |
| 235 | pub const Signature = struct { |
| 236 | /// Length (in bytes) of a raw signature. |
| 237 | pub const encoded_length = Curve.encoded_length + @sizeOf(CompressedScalar); |
| 238 | |
| 239 | /// The R component of an EdDSA signature. |
| 240 | r: [Curve.encoded_length]u8, |
| 241 | /// The S component of an EdDSA signature. |
| 242 | s: CompressedScalar, |
| 243 | |
| 244 | /// Return the raw signature (r, s) in little-endian format. |
| 245 | pub fn toBytes(sig: Signature) [encoded_length]u8 { |
| 246 | var bytes: [encoded_length]u8 = undefined; |
| 247 | bytes[0..Curve.encoded_length].* = sig.r; |
| 248 | bytes[Curve.encoded_length..].* = sig.s; |
| 249 | return bytes; |
| 250 | } |
| 251 | |
| 252 | /// Create a signature from a raw encoding of (r, s). |
| 253 | /// EdDSA always assumes little-endian. |
| 254 | pub fn fromBytes(bytes: [encoded_length]u8) Signature { |
| 255 | return Signature{ |
| 256 | .r = bytes[0..Curve.encoded_length].*, |
| 257 | .s = bytes[Curve.encoded_length..].*, |
| 258 | }; |
| 259 | } |
| 260 | |
| 261 | /// Create a Verifier for incremental verification of a signature. |
| 262 | pub fn verifier(sig: Signature, public_key: PublicKey) Verifier.InitError!Verifier { |
| 263 | return Verifier.init(sig, public_key); |
| 264 | } |
| 265 | |
| 266 | pub const VerifyError = Verifier.InitError || Verifier.VerifyError; |
| 267 | |
| 268 | /// Verify the signature against a message and public key. |
| 269 | /// |
| 270 | /// This function uses cofactored verification for broad interoperability. |
| 271 | /// It aligns single-signature verification with common batch verification approaches. |
| 272 | /// |
| 273 | /// Return IdentityElement or NonCanonical if the public key or signature are not in the expected range, |
| 274 | /// or SignatureVerificationError if the signature is invalid for the given message and key. |
| 275 | pub fn verify(sig: Signature, msg: []const u8, public_key: PublicKey) VerifyError!void { |
| 276 | var st = try sig.verifier(public_key); |
| 277 | st.update(msg); |
| 278 | try st.verify(); |
| 279 | } |
| 280 | |
| 281 | /// Verify the signature against a message and public key using cofactorless verification. |
| 282 | /// |
| 283 | /// This performs strict verification without cofactor multiplication, |
| 284 | /// checking the exact equation: [s]B = R + [H(R,A,m)]A |
| 285 | /// |
| 286 | /// This is more restrictive than the standard `verify()` method and may reject |
| 287 | /// specially crafted signatures that would be accepted by cofactored verification. |
| 288 | /// But it will never reject valid signatures created using the `sign()` method. |
| 289 | /// |
| 290 | /// Return IdentityElement or NonCanonical if the public key or signature are not in the expected range, |
| 291 | /// or SignatureVerificationError if the signature is invalid for the given message and key. |
| 292 | pub fn verifyStrict(sig: Signature, msg: []const u8, public_key: PublicKey) VerifyError!void { |
| 293 | var st = try sig.verifier(public_key); |
| 294 | st.update(msg); |
| 295 | try st.verifyStrict(); |
| 296 | } |
| 297 | }; |
| 298 | |
| 299 | /// An Ed25519 key pair. |
| 300 | pub const KeyPair = struct { |
| 301 | /// Length (in bytes) of a seed required to create a key pair. |
| 302 | pub const seed_length = noise_length; |
| 303 | |
| 304 | /// Public part. |
| 305 | public_key: PublicKey, |
| 306 | /// Secret scalar. |
| 307 | secret_key: SecretKey, |
| 308 | |
| 309 | /// Deterministically derive a key pair from a cryptograpically secure secret seed. |
| 310 | /// |
| 311 | /// To create a new key, applications should generally call `generate()` instead of this function. |
| 312 | /// |
| 313 | /// As in RFC 8032, an Ed25519 public key is generated by hashing |
| 314 | /// the secret key using the SHA-512 function, and interpreting the |
| 315 | /// bit-swapped, clamped lower-half of the output as the secret scalar. |
| 316 | /// |
| 317 | /// For this reason, an EdDSA secret key is commonly called a seed, |
| 318 | /// from which the actual secret is derived. |
| 319 | pub fn generateDeterministic(seed: [seed_length]u8) IdentityElementError!KeyPair { |
| 320 | var az: [Sha512.digest_length]u8 = undefined; |
| 321 | var h = Sha512.init(.{}); |
| 322 | h.update(&seed); |
| 323 | h.final(&az); |
| 324 | const pk_p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; |
| 325 | const pk_bytes = pk_p.toBytes(); |
| 326 | var sk_bytes: [SecretKey.encoded_length]u8 = undefined; |
| 327 | sk_bytes[0..seed_length].* = seed; |
| 328 | sk_bytes[seed_length..].* = pk_bytes; |
| 329 | return KeyPair{ |
| 330 | .public_key = PublicKey.fromBytes(pk_bytes) catch unreachable, |
| 331 | .secret_key = try SecretKey.fromBytes(sk_bytes), |
| 332 | }; |
| 333 | } |
| 334 | |
| 335 | /// Generate a new, random key pair. |
| 336 | pub fn generate(io: std.Io) KeyPair { |
| 337 | var random_seed: [seed_length]u8 = undefined; |
| 338 | while (true) { |
| 339 | io.random(&random_seed); |
| 340 | return generateDeterministic(random_seed) catch { |
| 341 | @branchHint(.unlikely); |
| 342 | continue; |
| 343 | }; |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// Create a key pair from an existing secret key. |
| 348 | /// |
| 349 | /// Note that with EdDSA, storing the seed, and recovering the key pair |
| 350 | /// from it is recommended over storing the entire secret key. |
| 351 | /// The seed of an exiting key pair can be obtained with |
| 352 | /// `key_pair.secret_key.seed()`, and the secret key can then be |
| 353 | /// recomputed using `SecretKey.generateDeterministic()`. |
| 354 | pub fn fromSecretKey(secret_key: SecretKey) (NonCanonicalError || EncodingError || IdentityElementError)!KeyPair { |
| 355 | // It is critical for EdDSA to use the correct public key. |
| 356 | // In order to enforce this, a SecretKey implicitly includes a copy of the public key. |
| 357 | // With runtime safety, we can still afford checking that the public key is correct. |
| 358 | if (std.debug.runtime_safety) { |
| 359 | const pk_p = try Curve.fromBytes(secret_key.publicKeyBytes()); |
| 360 | const recomputed_kp = try generateDeterministic(secret_key.seed()); |
| 361 | if (!mem.eql(u8, &recomputed_kp.public_key.toBytes(), &pk_p.toBytes())) { |
| 362 | return error.NonCanonical; |
| 363 | } |
| 364 | } |
| 365 | return KeyPair{ |
| 366 | .public_key = try PublicKey.fromBytes(secret_key.publicKeyBytes()), |
| 367 | .secret_key = secret_key, |
| 368 | }; |
| 369 | } |
| 370 | |
| 371 | /// Sign a message using the key pair. |
| 372 | /// The noise can be null in order to create deterministic signatures. |
| 373 | /// If deterministic signatures are not required, the noise should be randomly generated instead. |
| 374 | /// This helps defend against fault attacks. |
| 375 | pub fn sign(key_pair: KeyPair, msg: []const u8, noise: ?[noise_length]u8) (IdentityElementError || NonCanonicalError || KeyMismatchError || WeakPublicKeyError)!Signature { |
| 376 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 377 | return error.KeyMismatch; |
| 378 | } |
| 379 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 380 | return key_pair.public_key.computeNonceAndSign( |
| 381 | msg, |
| 382 | noise, |
| 383 | scalar_and_prefix.scalar, |
| 384 | &scalar_and_prefix.prefix, |
| 385 | ); |
| 386 | } |
| 387 | |
| 388 | /// Create a signer that can be used for incremental signing, using a custom base nonce. |
| 389 | /// `base_nonce` must be unique for each signed message; otherwise, the secret key can |
| 390 | /// be trivially recovered by an attacker. |
| 391 | /// It can be generated using a cryptographically secure random number generator. |
| 392 | pub fn signerWithBaseNonce( |
| 393 | key_pair: KeyPair, |
| 394 | base_nonce: [32]u8, |
| 395 | /// If set, should be something unique for each message, such as a counter. |
| 396 | noise: ?[noise_length]u8, |
| 397 | ) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signer { |
| 398 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 399 | return error.KeyMismatch; |
| 400 | } |
| 401 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 402 | var h = Sha512.init(.{}); |
| 403 | h.update(&scalar_and_prefix.prefix); |
| 404 | h.update(&base_nonce); |
| 405 | if (noise) |*z| { |
| 406 | h.update(z); |
| 407 | } |
| 408 | var nonce64: [64]u8 = undefined; |
| 409 | h.final(&nonce64); |
| 410 | const nonce = Curve.scalar.reduce64(nonce64); |
| 411 | |
| 412 | return Signer.init(scalar_and_prefix.scalar, nonce, key_pair.public_key); |
| 413 | } |
| 414 | |
| 415 | /// Create a Signer, that can be used for incremental signing. |
| 416 | /// Note that the signature is not deterministic. |
| 417 | pub fn signer( |
| 418 | key_pair: KeyPair, |
| 419 | /// If set, should be something unique for each message, such as a |
| 420 | /// random nonce, or a counter. |
| 421 | noise: ?[noise_length]u8, |
| 422 | io: std.Io, |
| 423 | ) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signer { |
| 424 | var base_nonce: [32]u8 = undefined; |
| 425 | io.random(&base_nonce); |
| 426 | return key_pair.signerWithBaseNonce(base_nonce, noise); |
| 427 | } |
| 428 | }; |
| 429 | |
| 430 | /// A (signature, message, public_key) tuple for batch verification |
| 431 | pub const BatchElement = struct { |
| 432 | sig: Signature, |
| 433 | msg: []const u8, |
| 434 | public_key: PublicKey, |
| 435 | }; |
| 436 | |
| 437 | /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one |
| 438 | pub fn verifyBatch(io: std.Io, comptime count: usize, signature_batch: [count]BatchElement) (SignatureVerificationError || IdentityElementError || WeakPublicKeyError || EncodingError || NonCanonicalError)!void { |
| 439 | var r_batch: [count]CompressedScalar = undefined; |
| 440 | var s_batch: [count]CompressedScalar = undefined; |
| 441 | var a_batch: [count]Curve = undefined; |
| 442 | var expected_r_batch: [count]Curve = undefined; |
| 443 | |
| 444 | for (signature_batch, 0..) |signature, i| { |
| 445 | const r = signature.sig.r; |
| 446 | const s = signature.sig.s; |
| 447 | try Curve.scalar.rejectNonCanonical(s); |
| 448 | const a = try Curve.fromBytes(signature.public_key.bytes); |
| 449 | try a.rejectIdentity(); |
| 450 | try Curve.rejectNonCanonical(r); |
| 451 | const expected_r = try Curve.fromBytes(r); |
| 452 | try expected_r.rejectIdentity(); |
| 453 | expected_r_batch[i] = expected_r; |
| 454 | r_batch[i] = r; |
| 455 | s_batch[i] = s; |
| 456 | a_batch[i] = a; |
| 457 | } |
| 458 | |
| 459 | var hram_batch: [count]Curve.scalar.CompressedScalar = undefined; |
| 460 | for (signature_batch, 0..) |signature, i| { |
| 461 | var h = Sha512.init(.{}); |
| 462 | h.update(&r_batch[i]); |
| 463 | h.update(&signature.public_key.bytes); |
| 464 | h.update(signature.msg); |
| 465 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 466 | h.final(&hram64); |
| 467 | hram_batch[i] = Curve.scalar.reduce64(hram64); |
| 468 | } |
| 469 | |
| 470 | var z_batch: [count]Curve.scalar.CompressedScalar = undefined; |
| 471 | for (&z_batch) |*z| { |
| 472 | io.random(z[0..16]); |
| 473 | @memset(z[16..], 0); |
| 474 | } |
| 475 | |
| 476 | var zs_sum = Curve.scalar.zero; |
| 477 | for (z_batch, 0..) |z, i| { |
| 478 | const zs = Curve.scalar.mul(z, s_batch[i]); |
| 479 | zs_sum = Curve.scalar.add(zs_sum, zs); |
| 480 | } |
| 481 | zs_sum = Curve.scalar.mul8(zs_sum); |
| 482 | |
| 483 | var zhs: [count]Curve.scalar.CompressedScalar = undefined; |
| 484 | for (z_batch, 0..) |z, i| { |
| 485 | zhs[i] = Curve.scalar.mul(z, hram_batch[i]); |
| 486 | } |
| 487 | |
| 488 | const zr = (try Curve.mulMulti(count, expected_r_batch, z_batch)).clearCofactor(); |
| 489 | const zah = (try Curve.mulMulti(count, a_batch, zhs)).clearCofactor(); |
| 490 | |
| 491 | const zsb = try Curve.basePoint.mulPublic(zs_sum); |
| 492 | if (zr.add(zah).sub(zsb).rejectIdentity()) |_| { |
| 493 | return error.SignatureVerificationFailed; |
| 494 | } else |_| {} |
| 495 | } |
| 496 | |
| 497 | /// Ed25519 signatures with key blinding. |
| 498 | pub const key_blinding = struct { |
| 499 | /// Length (in bytes) of a blinding seed. |
| 500 | pub const blind_seed_length = 32; |
| 501 | |
| 502 | /// A blind secret key. |
| 503 | pub const BlindSecretKey = struct { |
| 504 | prefix: [64]u8, |
| 505 | blind_scalar: CompressedScalar, |
| 506 | blind_public_key: BlindPublicKey, |
| 507 | }; |
| 508 | |
| 509 | /// A blind public key. |
| 510 | pub const BlindPublicKey = struct { |
| 511 | /// Public key equivalent, that can used for signature verification. |
| 512 | key: PublicKey, |
| 513 | |
| 514 | /// Recover a public key from a blind version of it. |
| 515 | pub fn unblind(blind_public_key: BlindPublicKey, blind_seed: [blind_seed_length]u8, ctx: []const u8) (IdentityElementError || NonCanonicalError || EncodingError || WeakPublicKeyError)!PublicKey { |
| 516 | const blind_h = blindCtx(blind_seed, ctx); |
| 517 | const inv_blind_factor = Scalar.fromBytes(blind_h[0..32].*).invert().toBytes(); |
| 518 | const pk_p = try (try Curve.fromBytes(blind_public_key.key.bytes)).mul(inv_blind_factor); |
| 519 | return PublicKey.fromBytes(pk_p.toBytes()); |
| 520 | } |
| 521 | }; |
| 522 | |
| 523 | /// A blind key pair. |
| 524 | pub const BlindKeyPair = struct { |
| 525 | blind_public_key: BlindPublicKey, |
| 526 | blind_secret_key: BlindSecretKey, |
| 527 | |
| 528 | /// Create an blind key pair from an existing key pair, a blinding seed and a context. |
| 529 | pub fn init(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8, ctx: []const u8) (NonCanonicalError || IdentityElementError)!BlindKeyPair { |
| 530 | var h: [Sha512.digest_length]u8 = undefined; |
| 531 | Sha512.hash(&key_pair.secret_key.seed(), &h, .{}); |
| 532 | Curve.scalar.clamp(h[0..32]); |
| 533 | const scalar = Curve.scalar.reduce(h[0..32].*); |
| 534 | |
| 535 | const blind_h = blindCtx(blind_seed, ctx); |
| 536 | const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); |
| 537 | |
| 538 | const blind_scalar = Curve.scalar.mul(scalar, blind_factor); |
| 539 | const blind_public_key = BlindPublicKey{ |
| 540 | .key = try PublicKey.fromBytes((Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes()), |
| 541 | }; |
| 542 | |
| 543 | var prefix: [64]u8 = undefined; |
| 544 | prefix[0..32].* = h[32..64].*; |
| 545 | prefix[32..64].* = blind_h[32..64].*; |
| 546 | |
| 547 | const blind_secret_key = BlindSecretKey{ |
| 548 | .prefix = prefix, |
| 549 | .blind_scalar = blind_scalar, |
| 550 | .blind_public_key = blind_public_key, |
| 551 | }; |
| 552 | return BlindKeyPair{ |
| 553 | .blind_public_key = blind_public_key, |
| 554 | .blind_secret_key = blind_secret_key, |
| 555 | }; |
| 556 | } |
| 557 | |
| 558 | /// Sign a message using a blind key pair, and optional random noise. |
| 559 | /// Having noise creates non-standard, non-deterministic signatures, |
| 560 | /// but has been proven to increase resilience against fault attacks. |
| 561 | pub fn sign(key_pair: BlindKeyPair, msg: []const u8, noise: ?[noise_length]u8) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signature { |
| 562 | const scalar = key_pair.blind_secret_key.blind_scalar; |
| 563 | const prefix = key_pair.blind_secret_key.prefix; |
| 564 | |
| 565 | return (try PublicKey.fromBytes(key_pair.blind_public_key.key.bytes)) |
| 566 | .computeNonceAndSign(msg, noise, scalar, &prefix); |
| 567 | } |
| 568 | }; |
| 569 | |
| 570 | /// Compute a blind context from a blinding seed and a context. |
| 571 | fn blindCtx(blind_seed: [blind_seed_length]u8, ctx: []const u8) [Sha512.digest_length]u8 { |
| 572 | var blind_h: [Sha512.digest_length]u8 = undefined; |
| 573 | var hx = Sha512.init(.{}); |
| 574 | hx.update(&blind_seed); |
| 575 | hx.update(&[1]u8{0}); |
| 576 | hx.update(ctx); |
| 577 | hx.final(&blind_h); |
| 578 | return blind_h; |
| 579 | } |
| 580 | }; |
| 581 | }; |
| 582 | |
| 583 | test "key pair creation" { |
| 584 | var seed: [32]u8 = undefined; |
| 585 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 586 | const key_pair = try Ed25519.KeyPair.generateDeterministic(seed); |
| 587 | var buf: [256]u8 = undefined; |
| 588 | try std.testing.expectEqualStrings(try std.mem.print(&buf, "{X}", .{&key_pair.secret_key.toBytes()}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 589 | try std.testing.expectEqualStrings(try std.mem.print(&buf, "{X}", .{&key_pair.public_key.toBytes()}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 590 | } |
| 591 | |
| 592 | test "signature" { |
| 593 | var seed: [32]u8 = undefined; |
| 594 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 595 | const key_pair = try Ed25519.KeyPair.generateDeterministic(seed); |
| 596 | |
| 597 | const sig = try key_pair.sign("test", null); |
| 598 | var buf: [128]u8 = undefined; |
| 599 | try std.testing.expectEqualStrings(try std.mem.print(&buf, "{X}", .{&sig.toBytes()}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); |
| 600 | try sig.verify("test", key_pair.public_key); |
| 601 | try std.testing.expectError(error.SignatureVerificationFailed, sig.verify("TEST", key_pair.public_key)); |
| 602 | } |
| 603 | |
| 604 | test "batch verification" { |
| 605 | const io = std.testing.io; |
| 606 | |
| 607 | for (0..16) |_| { |
| 608 | const key_pair = Ed25519.KeyPair.generate(io); |
| 609 | var msg1: [32]u8 = undefined; |
| 610 | var msg2: [32]u8 = undefined; |
| 611 | io.random(&msg1); |
| 612 | io.random(&msg2); |
| 613 | const sig1 = try key_pair.sign(&msg1, null); |
| 614 | const sig2 = try key_pair.sign(&msg2, null); |
| 615 | var signature_batch = [_]Ed25519.BatchElement{ |
| 616 | Ed25519.BatchElement{ |
| 617 | .sig = sig1, |
| 618 | .msg = &msg1, |
| 619 | .public_key = key_pair.public_key, |
| 620 | }, |
| 621 | Ed25519.BatchElement{ |
| 622 | .sig = sig2, |
| 623 | .msg = &msg2, |
| 624 | .public_key = key_pair.public_key, |
| 625 | }, |
| 626 | }; |
| 627 | try Ed25519.verifyBatch(io, 2, signature_batch); |
| 628 | |
| 629 | signature_batch[1].sig = sig1; |
| 630 | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(io, signature_batch.len, signature_batch)); |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | test "test vectors" { |
| 635 | const Vec = struct { |
| 636 | msg_hex: []const u8, |
| 637 | public_key_hex: *const [64:0]u8, |
| 638 | sig_hex: *const [128:0]u8, |
| 639 | expected: ?anyerror, |
| 640 | }; |
| 641 | |
| 642 | const entries = [_]Vec{ |
| 643 | Vec{ |
| 644 | .msg_hex = "8c93255d71dcab10e8f379c26200f3c7bd5f09d9bc3068d3ef4edeb4853022b6", |
| 645 | .public_key_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", |
| 646 | .sig_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a0000000000000000000000000000000000000000000000000000000000000000", |
| 647 | .expected = error.WeakPublicKey, // 0 |
| 648 | }, |
| 649 | Vec{ |
| 650 | .msg_hex = "9bd9f44f4dcc75bd531b56b2cd280b0bb38fc1cd6d1230e14861d861de092e79", |
| 651 | .public_key_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", |
| 652 | .sig_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43a5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", |
| 653 | .expected = error.WeakPublicKey, // 1 |
| 654 | }, |
| 655 | Vec{ |
| 656 | .msg_hex = "aebf3f2601a0c8c5d39cc7d8911642f740b78168218da8471772b35f9d35b9ab", |
| 657 | .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", |
| 658 | .sig_hex = "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa8c4bd45aecaca5b24fb97bc10ac27ac8751a7dfe1baff8b953ec9f5833ca260e", |
| 659 | .expected = null, // 2 - small order R is acceptable |
| 660 | }, |
| 661 | Vec{ |
| 662 | .msg_hex = "9bd9f44f4dcc75bd531b56b2cd280b0bb38fc1cd6d1230e14861d861de092e79", |
| 663 | .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", |
| 664 | .sig_hex = "9046a64750444938de19f227bb80485e92b83fdb4b6506c160484c016cc1852f87909e14428a7a1d62e9f22f3d3ad7802db02eb2e688b6c52fcd6648a98bd009", |
| 665 | .expected = null, // 3 - mixed orders |
| 666 | }, |
| 667 | Vec{ |
| 668 | .msg_hex = "e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec4011eaccd55b53f56c", |
| 669 | .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", |
| 670 | .sig_hex = "160a1cb0dc9c0258cd0a7d23e94d8fa878bcb1925f2c64246b2dee1796bed5125ec6bc982a269b723e0668e540911a9a6a58921d6925e434ab10aa7940551a09", |
| 671 | .expected = null, // 4 - cofactored verification |
| 672 | }, |
| 673 | Vec{ |
| 674 | .msg_hex = "e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec4011eaccd55b53f56c", |
| 675 | .public_key_hex = "cdb267ce40c5cd45306fa5d2f29731459387dbf9eb933b7bd5aed9a765b88d4d", |
| 676 | .sig_hex = "21122a84e0b5fca4052f5b1235c80a537878b38f3142356b2c2384ebad4668b7e40bc836dac0f71076f9abe3a53f9c03c1ceeeddb658d0030494ace586687405", |
| 677 | .expected = null, // 5 - cofactored verification |
| 678 | }, |
| 679 | Vec{ |
| 680 | .msg_hex = "85e241a07d148b41e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec40", |
| 681 | .public_key_hex = "442aad9f089ad9e14647b1ef9099a1ff4798d78589e66f28eca69c11f582a623", |
| 682 | .sig_hex = "e96f66be976d82e60150baecff9906684aebb1ef181f67a7189ac78ea23b6c0e547f7690a0e2ddcd04d87dbc3490dc19b3b3052f7ff0538cb68afb369ba3a514", |
| 683 | .expected = error.NonCanonical, // 6 - S > L |
| 684 | }, |
| 685 | Vec{ |
| 686 | .msg_hex = "85e241a07d148b41e47d62c63f830dc7a6851a0b1f33ae4bb2f507fb6cffec40", |
| 687 | .public_key_hex = "442aad9f089ad9e14647b1ef9099a1ff4798d78589e66f28eca69c11f582a623", |
| 688 | .sig_hex = "8ce5b96c8f26d0ab6c47958c9e68b937104cd36e13c33566acd2fe8d38aa19427e71f98a473474f2f13f06f97c20d58cc3f54b8bd0d272f42b695dd7e89a8c22", |
| 689 | .expected = error.NonCanonical, // 7 - S >> L |
| 690 | }, |
| 691 | Vec{ |
| 692 | .msg_hex = "9bedc267423725d473888631ebf45988bad3db83851ee85c85e241a07d148b41", |
| 693 | .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", |
| 694 | .sig_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff03be9678ac102edcd92b0210bb34d7428d12ffc5df5f37e359941266a4e35f0f", |
| 695 | .expected = error.IdentityElement, // 8 - non-canonical R |
| 696 | }, |
| 697 | Vec{ |
| 698 | .msg_hex = "9bedc267423725d473888631ebf45988bad3db83851ee85c85e241a07d148b41", |
| 699 | .public_key_hex = "f7badec5b8abeaf699583992219b7b223f1df3fbbea919844e3f7c554a43dd43", |
| 700 | .sig_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffca8c5b64cd208982aa38d4936621a4775aa233aa0505711d8fdcfdaa943d4908", |
| 701 | .expected = error.IdentityElement, // 9 - non-canonical R |
| 702 | }, |
| 703 | Vec{ |
| 704 | .msg_hex = "e96b7021eb39c1a163b6da4e3093dcd3f21387da4cc4572be588fafae23c155b", |
| 705 | .public_key_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", |
| 706 | .sig_hex = "a9d55260f765261eb9b84e106f665e00b867287a761990d7135963ee0a7d59dca5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", |
| 707 | .expected = error.IdentityElement, // 10 - small-order A |
| 708 | }, |
| 709 | Vec{ |
| 710 | .msg_hex = "39a591f5321bbe07fd5a23dc2f39d025d74526615746727ceefd6e82ae65c06f", |
| 711 | .public_key_hex = "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", |
| 712 | .sig_hex = "a9d55260f765261eb9b84e106f665e00b867287a761990d7135963ee0a7d59dca5bb704786be79fc476f91d3f3f89b03984d8068dcf1bb7dfc6637b45450ac04", |
| 713 | .expected = error.IdentityElement, // 11 - small-order A |
| 714 | }, |
| 715 | }; |
| 716 | for (entries) |entry| { |
| 717 | var msg: [64 / 2]u8 = undefined; |
| 718 | const msg_len = entry.msg_hex.len / 2; |
| 719 | _ = try fmt.hexToBytes(msg[0..msg_len], entry.msg_hex); |
| 720 | var public_key_bytes: [32]u8 = undefined; |
| 721 | _ = try fmt.hexToBytes(&public_key_bytes, entry.public_key_hex); |
| 722 | const public_key = Ed25519.PublicKey.fromBytes(public_key_bytes) catch |err| { |
| 723 | try std.testing.expectEqual(entry.expected.?, err); |
| 724 | continue; |
| 725 | }; |
| 726 | var sig_bytes: [64]u8 = undefined; |
| 727 | _ = try fmt.hexToBytes(&sig_bytes, entry.sig_hex); |
| 728 | const sig = Ed25519.Signature.fromBytes(sig_bytes); |
| 729 | if (entry.expected) |error_type| { |
| 730 | try std.testing.expectError(error_type, sig.verify(msg[0..msg_len], public_key)); |
| 731 | } else { |
| 732 | try sig.verify(msg[0..msg_len], public_key); |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | test "with blind keys" { |
| 738 | const io = std.testing.io; |
| 739 | const BlindKeyPair = Ed25519.key_blinding.BlindKeyPair; |
| 740 | |
| 741 | // Create a standard Ed25519 key pair |
| 742 | const kp = Ed25519.KeyPair.generate(io); |
| 743 | |
| 744 | // Create a random blinding seed |
| 745 | var blind: [32]u8 = undefined; |
| 746 | io.random(&blind); |
| 747 | |
| 748 | // Blind the key pair |
| 749 | const blind_kp = try BlindKeyPair.init(kp, blind, "ctx"); |
| 750 | |
| 751 | // Sign a message and check that it can be verified with the blind public key |
| 752 | const msg = "test"; |
| 753 | const sig = try blind_kp.sign(msg, null); |
| 754 | try sig.verify(msg, blind_kp.blind_public_key.key); |
| 755 | |
| 756 | // Unblind the public key |
| 757 | const pk = try blind_kp.blind_public_key.unblind(blind, "ctx"); |
| 758 | try std.testing.expectEqualSlices(u8, &pk.toBytes(), &kp.public_key.toBytes()); |
| 759 | } |
| 760 | |
| 761 | test "signatures with streaming" { |
| 762 | const io = std.testing.io; |
| 763 | const kp = Ed25519.KeyPair.generate(io); |
| 764 | |
| 765 | var signer = try kp.signer(null, io); |
| 766 | signer.update("mes"); |
| 767 | signer.update("sage"); |
| 768 | const sig = signer.finalize(); |
| 769 | |
| 770 | try sig.verify("message", kp.public_key); |
| 771 | |
| 772 | var verifier = try sig.verifier(kp.public_key); |
| 773 | verifier.update("mess"); |
| 774 | verifier.update("age"); |
| 775 | try verifier.verify(); |
| 776 | } |
| 777 | |
| 778 | test "key pair from secret key" { |
| 779 | const io = std.testing.io; |
| 780 | const kp = Ed25519.KeyPair.generate(io); |
| 781 | const kp2 = try Ed25519.KeyPair.fromSecretKey(kp.secret_key); |
| 782 | try std.testing.expectEqualSlices(u8, &kp.secret_key.toBytes(), &kp2.secret_key.toBytes()); |
| 783 | try std.testing.expectEqualSlices(u8, &kp.public_key.toBytes(), &kp2.public_key.toBytes()); |
| 784 | } |
| 785 | |
| 786 | test "cofactored vs cofactorless verification" { |
| 787 | const msg_hex = "65643235353139766563746f72732033"; |
| 788 | const public_key_hex = "86e72f5c2a7215151059aa151c0ee6f8e2155d301402f35d7498f078629a8f79"; |
| 789 | const sig_hex = "fa9dde274f4820efb19a890f8ba2d8791710a4303ceef4aedf9dddc4e81a1f11701a598b9a02ae60505dd0c2938a1a0c2d6ffd4676cfb49125b19e9cb358da06"; |
| 790 | |
| 791 | var msg: [16]u8 = undefined; |
| 792 | _ = try fmt.hexToBytes(&msg, msg_hex); |
| 793 | |
| 794 | var pk_bytes: [32]u8 = undefined; |
| 795 | _ = try fmt.hexToBytes(&pk_bytes, public_key_hex); |
| 796 | const pk = try Ed25519.PublicKey.fromBytes(pk_bytes); |
| 797 | |
| 798 | var sig_bytes: [64]u8 = undefined; |
| 799 | _ = try fmt.hexToBytes(&sig_bytes, sig_hex); |
| 800 | const sig = Ed25519.Signature.fromBytes(sig_bytes); |
| 801 | |
| 802 | try sig.verify(&msg, pk); |
| 803 | |
| 804 | try std.testing.expectError( |
| 805 | error.SignatureVerificationFailed, |
| 806 | sig.verifyStrict(&msg, pk), |
| 807 | ); |
| 808 | } |
| 809 | |
| 810 | test "regular signature verifies with both verify and verifyStrict" { |
| 811 | const io = std.testing.io; |
| 812 | const kp = Ed25519.KeyPair.generate(io); |
| 813 | const msg = "test message"; |
| 814 | const sig = try kp.sign(msg, null); |
| 815 | try sig.verify(msg, kp.public_key); |
| 816 | try sig.verifyStrict(msg, kp.public_key); |
| 817 | } |