| ... | ... | @@ -16,27 +16,227 @@ const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; |
| 16 | 16 | /// Ed25519 (EdDSA) signatures. |
| 17 | 17 | pub const Ed25519 = struct { |
| 18 | 18 | /// The underlying elliptic curve. |
| 19 | | pub const Curve = @import("edwards25519.zig").Edwards25519; |
| 20 | | /// Length (in bytes) of a seed required to create a key pair. |
| 21 | | pub const seed_length = 32; |
| 22 | | /// Length (in bytes) of a compressed secret key. |
| 23 | | pub const secret_length = 64; |
| 24 | | /// Length (in bytes) of a compressed public key. |
| 25 | | pub const public_length = 32; |
| 26 | | /// Length (in bytes) of a signature. |
| 27 | | pub const signature_length = 64; |
| 19 | pub const Curve = std.crypto.ecc.Edwards25519; |
| 20 | |
| 28 | 21 | /// Length (in bytes) of optional random bytes, for non-deterministic signatures. |
| 29 | 22 | pub const noise_length = 32; |
| 30 | 23 | |
| 31 | 24 | const CompressedScalar = Curve.scalar.CompressedScalar; |
| 32 | 25 | const Scalar = Curve.scalar.Scalar; |
| 33 | 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 | mem.copy(u8, t[0..32], &r_bytes); |
| 82 | mem.copy(u8, 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 | fn init(sig: Signature, public_key: PublicKey) (NonCanonicalError || EncodingError || IdentityElementError)!Verifier { |
| 155 | const r = sig.r; |
| 156 | const s = sig.s; |
| 157 | try Curve.scalar.rejectNonCanonical(s); |
| 158 | const a = try Curve.fromBytes(public_key.bytes); |
| 159 | try a.rejectIdentity(); |
| 160 | try Curve.rejectNonCanonical(r); |
| 161 | const expected_r = try Curve.fromBytes(r); |
| 162 | try expected_r.rejectIdentity(); |
| 163 | |
| 164 | var h = Sha512.init(.{}); |
| 165 | h.update(&r); |
| 166 | h.update(&public_key.bytes); |
| 167 | |
| 168 | return Verifier{ .h = h, .s = s, .a = a, .expected_r = expected_r }; |
| 169 | } |
| 170 | |
| 171 | /// Add new content to the message to be verified. |
| 172 | pub fn update(self: *Verifier, msg: []const u8) void { |
| 173 | self.h.update(msg); |
| 174 | } |
| 175 | |
| 176 | /// Verify that the signature is valid for the entire message. |
| 177 | pub fn verify(self: *Verifier) (SignatureVerificationError || WeakPublicKeyError || IdentityElementError)!void { |
| 178 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 179 | self.h.final(&hram64); |
| 180 | const hram = Curve.scalar.reduce64(hram64); |
| 181 | |
| 182 | const sb_ah = try Curve.basePoint.mulDoubleBasePublic(self.s, self.a.neg(), hram); |
| 183 | if (self.expected_r.sub(sb_ah).clearCofactor().rejectIdentity()) |_| { |
| 184 | return error.SignatureVerificationFailed; |
| 185 | } else |_| {} |
| 186 | } |
| 187 | }; |
| 188 | |
| 189 | /// An Ed25519 signature. |
| 190 | pub const Signature = struct { |
| 191 | /// Length (in bytes) of a raw signature. |
| 192 | pub const encoded_length = Curve.encoded_length + @sizeOf(CompressedScalar); |
| 193 | |
| 194 | /// The R component of an EdDSA signature. |
| 195 | r: [Curve.encoded_length]u8, |
| 196 | /// The S component of an EdDSA signature. |
| 197 | s: CompressedScalar, |
| 198 | |
| 199 | /// Return the raw signature (r, s) in little-endian format. |
| 200 | pub fn toBytes(self: Signature) [encoded_length]u8 { |
| 201 | var bytes: [encoded_length]u8 = undefined; |
| 202 | mem.copy(u8, bytes[0 .. encoded_length / 2], &self.r); |
| 203 | mem.copy(u8, bytes[encoded_length / 2 ..], &self.s); |
| 204 | return bytes; |
| 205 | } |
| 206 | |
| 207 | /// Create a signature from a raw encoding of (r, s). |
| 208 | /// EdDSA always assumes little-endian. |
| 209 | pub fn fromBytes(bytes: [encoded_length]u8) Signature { |
| 210 | return Signature{ |
| 211 | .r = bytes[0 .. encoded_length / 2].*, |
| 212 | .s = bytes[encoded_length / 2 ..].*, |
| 213 | }; |
| 214 | } |
| 215 | |
| 216 | /// Create a Verifier for incremental verification of a signature. |
| 217 | pub fn verifier(self: Signature, public_key: PublicKey) (NonCanonicalError || EncodingError || IdentityElementError)!Verifier { |
| 218 | return Verifier.init(self, public_key); |
| 219 | } |
| 220 | |
| 221 | /// Verify the signature against a message and public key. |
| 222 | /// Return IdentityElement or NonCanonical if the public key or signature are not in the expected range, |
| 223 | /// or SignatureVerificationError if the signature is invalid for the given message and key. |
| 224 | pub fn verify(self: Signature, msg: []const u8, public_key: PublicKey) (IdentityElementError || NonCanonicalError || SignatureVerificationError || EncodingError || WeakPublicKeyError)!void { |
| 225 | var st = try Verifier.init(self, public_key); |
| 226 | st.update(msg); |
| 227 | return st.verify(); |
| 228 | } |
| 229 | }; |
| 230 | |
| 34 | 231 | /// An Ed25519 key pair. |
| 35 | 232 | pub const KeyPair = struct { |
| 233 | /// Length (in bytes) of a seed required to create a key pair. |
| 234 | pub const seed_length = noise_length; |
| 235 | |
| 36 | 236 | /// Public part. |
| 37 | | public_key: [public_length]u8, |
| 38 | | /// Secret part. What we expose as a secret key is, under the hood, the concatenation of the seed and the public key. |
| 39 | | secret_key: [secret_length]u8, |
| 237 | public_key: PublicKey, |
| 238 | /// Secret scalar. |
| 239 | secret_key: SecretKey, |
| 40 | 240 | |
| 41 | 241 | /// Derive a key pair from an optional secret seed. |
| 42 | 242 | /// |
| ... | ... | @@ -56,120 +256,101 @@ pub const Ed25519 = struct { |
| 56 | 256 | var h = Sha512.init(.{}); |
| 57 | 257 | h.update(&ss); |
| 58 | 258 | h.final(&az); |
| 59 | | const p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; |
| 60 | | var sk: [secret_length]u8 = undefined; |
| 61 | | mem.copy(u8, &sk, &ss); |
| 62 | | const pk = p.toBytes(); |
| 63 | | mem.copy(u8, sk[seed_length..], &pk); |
| 64 | | |
| 65 | | return KeyPair{ .public_key = pk, .secret_key = sk }; |
| 259 | const pk_p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; |
| 260 | const pk_bytes = pk_p.toBytes(); |
| 261 | var sk_bytes: [SecretKey.encoded_length]u8 = undefined; |
| 262 | mem.copy(u8, &sk_bytes, &ss); |
| 263 | mem.copy(u8, sk_bytes[seed_length..], &pk_bytes); |
| 264 | return KeyPair{ |
| 265 | .public_key = PublicKey.fromBytes(pk_bytes) catch unreachable, |
| 266 | .secret_key = try SecretKey.fromBytes(sk_bytes), |
| 267 | }; |
| 66 | 268 | } |
| 67 | 269 | |
| 68 | 270 | /// Create a KeyPair from a secret key. |
| 69 | | pub fn fromSecretKey(secret_key: [secret_length]u8) KeyPair { |
| 271 | pub fn fromSecretKey(secret_key: SecretKey) IdentityElementError!KeyPair { |
| 272 | const pk_p = try Curve.fromBytes(secret_key.publicKeyBytes()); |
| 273 | |
| 274 | // It is critical for EdDSA to use the correct public key. |
| 275 | // In order to enforce this, a SecretKey implicitly includes a copy of the public key. |
| 276 | // In Debug mode, we can still afford checking that the public key is correct for extra safety. |
| 277 | if (std.builtin.mode == .Debug) { |
| 278 | const recomputed_kp = try create(secret_key[0..seed_length].*); |
| 279 | debug.assert(recomputed_kp.public_key.p.toBytes() == pk_p.toBytes()); |
| 280 | } |
| 70 | 281 | return KeyPair{ |
| 282 | .public_key = PublicKey{ .p = pk_p }, |
| 71 | 283 | .secret_key = secret_key, |
| 72 | | .public_key = secret_key[seed_length..].*, |
| 73 | 284 | }; |
| 74 | 285 | } |
| 75 | | }; |
| 76 | 286 | |
| 77 | | /// Sign a message using a key pair, and optional random noise. |
| 78 | | /// Having noise creates non-standard, non-deterministic signatures, |
| 79 | | /// but has been proven to increase resilience against fault attacks. |
| 80 | | pub fn sign(msg: []const u8, key_pair: KeyPair, noise: ?[noise_length]u8) (IdentityElementError || WeakPublicKeyError || KeyMismatchError)![signature_length]u8 { |
| 81 | | const seed = key_pair.secret_key[0..seed_length]; |
| 82 | | const public_key = key_pair.secret_key[seed_length..]; |
| 83 | | if (!mem.eql(u8, public_key, &key_pair.public_key)) { |
| 84 | | return error.KeyMismatch; |
| 85 | | } |
| 86 | | var az: [Sha512.digest_length]u8 = undefined; |
| 87 | | var h = Sha512.init(.{}); |
| 88 | | h.update(seed); |
| 89 | | h.final(&az); |
| 90 | | |
| 91 | | h = Sha512.init(.{}); |
| 92 | | if (noise) |*z| { |
| 93 | | h.update(z); |
| 287 | /// Sign a message using the key pair. |
| 288 | /// The noise can be null in order to create deterministic signatures. |
| 289 | /// If deterministic signatures are not required, the noise should be randomly generated instead. |
| 290 | /// This helps defend against fault attacks. |
| 291 | pub fn sign(key_pair: KeyPair, msg: []const u8, noise: ?[noise_length]u8) (IdentityElementError || NonCanonicalError || KeyMismatchError || WeakPublicKeyError)!Signature { |
| 292 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 293 | return error.KeyMismatch; |
| 294 | } |
| 295 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 296 | return key_pair.public_key.computeNonceAndSign( |
| 297 | msg, |
| 298 | noise, |
| 299 | scalar_and_prefix.scalar, |
| 300 | &scalar_and_prefix.prefix, |
| 301 | ); |
| 94 | 302 | } |
| 95 | | h.update(az[32..]); |
| 96 | | h.update(msg); |
| 97 | | var nonce64: [64]u8 = undefined; |
| 98 | | h.final(&nonce64); |
| 99 | | const nonce = Curve.scalar.reduce64(nonce64); |
| 100 | | const r = try Curve.basePoint.mul(nonce); |
| 101 | | |
| 102 | | var sig: [signature_length]u8 = undefined; |
| 103 | | mem.copy(u8, sig[0..32], &r.toBytes()); |
| 104 | | mem.copy(u8, sig[32..], public_key); |
| 105 | | h = Sha512.init(.{}); |
| 106 | | h.update(&sig); |
| 107 | | h.update(msg); |
| 108 | | var hram64: [Sha512.digest_length]u8 = undefined; |
| 109 | | h.final(&hram64); |
| 110 | | const hram = Curve.scalar.reduce64(hram64); |
| 111 | | |
| 112 | | var x = az[0..32]; |
| 113 | | Curve.scalar.clamp(x); |
| 114 | | const s = Curve.scalar.mulAdd(hram, x.*, nonce); |
| 115 | | mem.copy(u8, sig[32..], s[0..]); |
| 116 | | return sig; |
| 117 | | } |
| 118 | 303 | |
| 119 | | /// Verify an Ed25519 signature given a message and a public key. |
| 120 | | /// Returns error.SignatureVerificationFailed is the signature verification failed. |
| 121 | | pub fn verify(sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8) (SignatureVerificationError || WeakPublicKeyError || EncodingError || NonCanonicalError || IdentityElementError)!void { |
| 122 | | const r = sig[0..32]; |
| 123 | | const s = sig[32..64]; |
| 124 | | try Curve.scalar.rejectNonCanonical(s.*); |
| 125 | | try Curve.rejectNonCanonical(public_key); |
| 126 | | const a = try Curve.fromBytes(public_key); |
| 127 | | try a.rejectIdentity(); |
| 128 | | try Curve.rejectNonCanonical(r.*); |
| 129 | | const expected_r = try Curve.fromBytes(r.*); |
| 130 | | try expected_r.rejectIdentity(); |
| 131 | | |
| 132 | | var h = Sha512.init(.{}); |
| 133 | | h.update(r); |
| 134 | | h.update(&public_key); |
| 135 | | h.update(msg); |
| 136 | | var hram64: [Sha512.digest_length]u8 = undefined; |
| 137 | | h.final(&hram64); |
| 138 | | const hram = Curve.scalar.reduce64(hram64); |
| 139 | | |
| 140 | | const sb_ah = try Curve.basePoint.mulDoubleBasePublic(s.*, a.neg(), hram); |
| 141 | | if (expected_r.sub(sb_ah).clearCofactor().rejectIdentity()) |_| { |
| 142 | | return error.SignatureVerificationFailed; |
| 143 | | } else |_| {} |
| 144 | | } |
| 304 | /// Create a Signer, that can be used for incremental signing. |
| 305 | /// Note that the signature is not deterministic. |
| 306 | /// The noise parameter, if set, should be something unique for each message, |
| 307 | /// such as a random nonce, or a counter. |
| 308 | pub fn signer(key_pair: KeyPair, noise: ?[noise_length]u8) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signer { |
| 309 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 310 | return error.KeyMismatch; |
| 311 | } |
| 312 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 313 | var h = Sha512.init(.{}); |
| 314 | h.update(&scalar_and_prefix.prefix); |
| 315 | var noise2: [noise_length]u8 = undefined; |
| 316 | crypto.random.bytes(&noise2); |
| 317 | if (noise) |*z| { |
| 318 | h.update(z); |
| 319 | } |
| 320 | var nonce64: [64]u8 = undefined; |
| 321 | h.final(&nonce64); |
| 322 | const nonce = Curve.scalar.reduce64(nonce64); |
| 323 | |
| 324 | return Signer.init(scalar_and_prefix.scalar, nonce, key_pair.public_key); |
| 325 | } |
| 326 | }; |
| 145 | 327 | |
| 146 | 328 | /// A (signature, message, public_key) tuple for batch verification |
| 147 | 329 | pub const BatchElement = struct { |
| 148 | | sig: [signature_length]u8, |
| 330 | sig: Signature, |
| 149 | 331 | msg: []const u8, |
| 150 | | public_key: [public_length]u8, |
| 332 | public_key: PublicKey, |
| 151 | 333 | }; |
| 152 | 334 | |
| 153 | 335 | /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one |
| 154 | 336 | pub fn verifyBatch(comptime count: usize, signature_batch: [count]BatchElement) (SignatureVerificationError || IdentityElementError || WeakPublicKeyError || EncodingError || NonCanonicalError)!void { |
| 155 | | var r_batch: [count][32]u8 = undefined; |
| 156 | | var s_batch: [count][32]u8 = undefined; |
| 337 | var r_batch: [count]CompressedScalar = undefined; |
| 338 | var s_batch: [count]CompressedScalar = undefined; |
| 157 | 339 | var a_batch: [count]Curve = undefined; |
| 158 | 340 | var expected_r_batch: [count]Curve = undefined; |
| 159 | 341 | |
| 160 | 342 | for (signature_batch) |signature, i| { |
| 161 | | const r = signature.sig[0..32]; |
| 162 | | const s = signature.sig[32..64]; |
| 163 | | try Curve.scalar.rejectNonCanonical(s.*); |
| 164 | | try Curve.rejectNonCanonical(signature.public_key); |
| 165 | | const a = try Curve.fromBytes(signature.public_key); |
| 343 | const r = signature.sig.r; |
| 344 | const s = signature.sig.s; |
| 345 | try Curve.scalar.rejectNonCanonical(s); |
| 346 | const a = try Curve.fromBytes(signature.public_key.bytes); |
| 166 | 347 | try a.rejectIdentity(); |
| 167 | | try Curve.rejectNonCanonical(r.*); |
| 168 | | const expected_r = try Curve.fromBytes(r.*); |
| 348 | try Curve.rejectNonCanonical(r); |
| 349 | const expected_r = try Curve.fromBytes(r); |
| 169 | 350 | try expected_r.rejectIdentity(); |
| 170 | 351 | expected_r_batch[i] = expected_r; |
| 171 | | r_batch[i] = r.*; |
| 172 | | s_batch[i] = s.*; |
| 352 | r_batch[i] = r; |
| 353 | s_batch[i] = s; |
| 173 | 354 | a_batch[i] = a; |
| 174 | 355 | } |
| 175 | 356 | |
| ... | ... | @@ -177,7 +358,7 @@ pub const Ed25519 = struct { |
| 177 | 358 | for (signature_batch) |signature, i| { |
| 178 | 359 | var h = Sha512.init(.{}); |
| 179 | 360 | h.update(&r_batch[i]); |
| 180 | | h.update(&signature.public_key); |
| 361 | h.update(&signature.public_key.bytes); |
| 181 | 362 | h.update(signature.msg); |
| 182 | 363 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 183 | 364 | h.final(&hram64); |
| ... | ... | @@ -212,7 +393,7 @@ pub const Ed25519 = struct { |
| 212 | 393 | } |
| 213 | 394 | |
| 214 | 395 | /// Ed25519 signatures with key blinding. |
| 215 | | pub const BlindKeySignatures = struct { |
| 396 | pub const key_blinding = struct { |
| 216 | 397 | /// Length (in bytes) of a blinding seed. |
| 217 | 398 | pub const blind_seed_length = 32; |
| 218 | 399 | |
| ... | ... | @@ -220,81 +401,69 @@ pub const Ed25519 = struct { |
| 220 | 401 | pub const BlindSecretKey = struct { |
| 221 | 402 | prefix: [64]u8, |
| 222 | 403 | blind_scalar: CompressedScalar, |
| 223 | | blind_public_key: CompressedScalar, |
| 404 | blind_public_key: BlindPublicKey, |
| 405 | }; |
| 406 | |
| 407 | /// A blind public key. |
| 408 | pub const BlindPublicKey = struct { |
| 409 | /// Public key equivalent, that can used for signature verification. |
| 410 | key: PublicKey, |
| 411 | |
| 412 | /// Recover a public key from a blind version of it. |
| 413 | pub fn unblind(blind_public_key: BlindPublicKey, blind_seed: [blind_seed_length]u8, ctx: []const u8) (IdentityElementError || NonCanonicalError || EncodingError || WeakPublicKeyError)!PublicKey { |
| 414 | const blind_h = blindCtx(blind_seed, ctx); |
| 415 | const inv_blind_factor = Scalar.fromBytes(blind_h[0..32].*).invert().toBytes(); |
| 416 | const pk_p = try (try Curve.fromBytes(blind_public_key.key.bytes)).mul(inv_blind_factor); |
| 417 | return PublicKey.fromBytes(pk_p.toBytes()); |
| 418 | } |
| 224 | 419 | }; |
| 225 | 420 | |
| 226 | 421 | /// A blind key pair. |
| 227 | 422 | pub const BlindKeyPair = struct { |
| 228 | | blind_public_key: [public_length]u8, |
| 423 | blind_public_key: BlindPublicKey, |
| 229 | 424 | blind_secret_key: BlindSecretKey, |
| 230 | | }; |
| 231 | 425 | |
| 232 | | /// Blind an existing key pair with a blinding seed and a context. |
| 233 | | pub fn blind(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8, ctx: []const u8) !BlindKeyPair { |
| 234 | | var h: [Sha512.digest_length]u8 = undefined; |
| 235 | | Sha512.hash(key_pair.secret_key[0..32], &h, .{}); |
| 236 | | Curve.scalar.clamp(h[0..32]); |
| 237 | | const scalar = Curve.scalar.reduce(h[0..32].*); |
| 238 | | |
| 239 | | const blind_h = blindCtx(blind_seed, ctx); |
| 240 | | const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); |
| 241 | | |
| 242 | | const blind_scalar = Curve.scalar.mul(scalar, blind_factor); |
| 243 | | const blind_public_key = (Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes(); |
| 244 | | |
| 245 | | var prefix: [64]u8 = undefined; |
| 246 | | mem.copy(u8, prefix[0..32], h[32..64]); |
| 247 | | mem.copy(u8, prefix[32..64], blind_h[32..64]); |
| 248 | | |
| 249 | | const blind_secret_key = .{ |
| 250 | | .prefix = prefix, |
| 251 | | .blind_scalar = blind_scalar, |
| 252 | | .blind_public_key = blind_public_key, |
| 253 | | }; |
| 254 | | return BlindKeyPair{ |
| 255 | | .blind_public_key = blind_public_key, |
| 256 | | .blind_secret_key = blind_secret_key, |
| 257 | | }; |
| 258 | | } |
| 259 | | |
| 260 | | /// Recover a public key from a blind version of it. |
| 261 | | pub fn unblindPublicKey(blind_public_key: [public_length]u8, blind_seed: [blind_seed_length]u8, ctx: []const u8) ![public_length]u8 { |
| 262 | | const blind_h = blindCtx(blind_seed, ctx); |
| 263 | | const inv_blind_factor = Scalar.fromBytes(blind_h[0..32].*).invert().toBytes(); |
| 264 | | const public_key = try (try Curve.fromBytes(blind_public_key)).mul(inv_blind_factor); |
| 265 | | return public_key.toBytes(); |
| 266 | | } |
| 267 | | |
| 268 | | /// Sign a message using a blind key pair, and optional random noise. |
| 269 | | /// Having noise creates non-standard, non-deterministic signatures, |
| 270 | | /// but has been proven to increase resilience against fault attacks. |
| 271 | | pub fn sign(msg: []const u8, key_pair: BlindKeyPair, noise: ?[noise_length]u8) ![signature_length]u8 { |
| 272 | | var h = Sha512.init(.{}); |
| 273 | | if (noise) |*z| { |
| 274 | | h.update(z); |
| 426 | /// Create an blind key pair from an existing key pair, a blinding seed and a context. |
| 427 | pub fn init(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8, ctx: []const u8) (NonCanonicalError || IdentityElementError)!BlindKeyPair { |
| 428 | var h: [Sha512.digest_length]u8 = undefined; |
| 429 | Sha512.hash(&key_pair.secret_key.seed(), &h, .{}); |
| 430 | Curve.scalar.clamp(h[0..32]); |
| 431 | const scalar = Curve.scalar.reduce(h[0..32].*); |
| 432 | |
| 433 | const blind_h = blindCtx(blind_seed, ctx); |
| 434 | const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); |
| 435 | |
| 436 | const blind_scalar = Curve.scalar.mul(scalar, blind_factor); |
| 437 | const blind_public_key = BlindPublicKey{ |
| 438 | .key = try PublicKey.fromBytes((Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes()), |
| 439 | }; |
| 440 | |
| 441 | var prefix: [64]u8 = undefined; |
| 442 | mem.copy(u8, prefix[0..32], h[32..64]); |
| 443 | mem.copy(u8, prefix[32..64], blind_h[32..64]); |
| 444 | |
| 445 | const blind_secret_key = BlindSecretKey{ |
| 446 | .prefix = prefix, |
| 447 | .blind_scalar = blind_scalar, |
| 448 | .blind_public_key = blind_public_key, |
| 449 | }; |
| 450 | return BlindKeyPair{ |
| 451 | .blind_public_key = blind_public_key, |
| 452 | .blind_secret_key = blind_secret_key, |
| 453 | }; |
| 275 | 454 | } |
| 276 | | h.update(&key_pair.blind_secret_key.prefix); |
| 277 | | h.update(msg); |
| 278 | | var nonce64: [64]u8 = undefined; |
| 279 | | h.final(&nonce64); |
| 280 | 455 | |
| 281 | | const nonce = Curve.scalar.reduce64(nonce64); |
| 282 | | const r = try Curve.basePoint.mul(nonce); |
| 456 | /// Sign a message using a blind key pair, and optional random noise. |
| 457 | /// Having noise creates non-standard, non-deterministic signatures, |
| 458 | /// but has been proven to increase resilience against fault attacks. |
| 459 | pub fn sign(key_pair: BlindKeyPair, msg: []const u8, noise: ?[noise_length]u8) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signature { |
| 460 | const scalar = key_pair.blind_secret_key.blind_scalar; |
| 461 | const prefix = key_pair.blind_secret_key.prefix; |
| 283 | 462 | |
| 284 | | var sig: [signature_length]u8 = undefined; |
| 285 | | mem.copy(u8, sig[0..32], &r.toBytes()); |
| 286 | | mem.copy(u8, sig[32..], &key_pair.blind_public_key); |
| 287 | | h = Sha512.init(.{}); |
| 288 | | h.update(&sig); |
| 289 | | h.update(msg); |
| 290 | | var hram64: [Sha512.digest_length]u8 = undefined; |
| 291 | | h.final(&hram64); |
| 292 | | const hram = Curve.scalar.reduce64(hram64); |
| 293 | | |
| 294 | | const s = Curve.scalar.mulAdd(hram, key_pair.blind_secret_key.blind_scalar, nonce); |
| 295 | | mem.copy(u8, sig[32..], s[0..]); |
| 296 | | return sig; |
| 297 | | } |
| 463 | return (try PublicKey.fromBytes(key_pair.blind_public_key.key.bytes)) |
| 464 | .computeNonceAndSign(msg, noise, scalar, &prefix); |
| 465 | } |
| 466 | }; |
| 298 | 467 | |
| 299 | 468 | /// Compute a blind context from a blinding seed and a context. |
| 300 | 469 | fn blindCtx(blind_seed: [blind_seed_length]u8, ctx: []const u8) [Sha512.digest_length]u8 { |
| ... | ... | @@ -306,7 +475,13 @@ pub const Ed25519 = struct { |
| 306 | 475 | hx.final(&blind_h); |
| 307 | 476 | return blind_h; |
| 308 | 477 | } |
| 478 | |
| 479 | pub const sign = @compileError("deprecated; use BlindKeyPair.sign instead"); |
| 480 | pub const unblindPublicKey = @compileError("deprecated; use BlindPublicKey.unblind instead"); |
| 309 | 481 | }; |
| 482 | |
| 483 | pub const sign = @compileError("deprecated; use KeyPair.sign instead"); |
| 484 | pub const verify = @compileError("deprecated; use PublicKey.verify instead"); |
| 310 | 485 | }; |
| 311 | 486 | |
| 312 | 487 | test "ed25519 key pair creation" { |
| ... | ... | @@ -314,8 +489,8 @@ test "ed25519 key pair creation" { |
| 314 | 489 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 315 | 490 | const key_pair = try Ed25519.KeyPair.create(seed); |
| 316 | 491 | var buf: [256]u8 = undefined; |
| 317 | | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key)}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 318 | | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key)}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 492 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key.toBytes())}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 493 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key.toBytes())}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 319 | 494 | } |
| 320 | 495 | |
| 321 | 496 | test "ed25519 signature" { |
| ... | ... | @@ -323,11 +498,11 @@ test "ed25519 signature" { |
| 323 | 498 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 324 | 499 | const key_pair = try Ed25519.KeyPair.create(seed); |
| 325 | 500 | |
| 326 | | const sig = try Ed25519.sign("test", key_pair, null); |
| 501 | const sig = try key_pair.sign("test", null); |
| 327 | 502 | var buf: [128]u8 = undefined; |
| 328 | | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig)}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); |
| 329 | | try Ed25519.verify(sig, "test", key_pair.public_key); |
| 330 | | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verify(sig, "TEST", key_pair.public_key)); |
| 503 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig.toBytes())}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); |
| 504 | try sig.verify("test", key_pair.public_key); |
| 505 | try std.testing.expectError(error.SignatureVerificationFailed, sig.verify("TEST", key_pair.public_key)); |
| 331 | 506 | } |
| 332 | 507 | |
| 333 | 508 | test "ed25519 batch verification" { |
| ... | ... | @@ -338,8 +513,8 @@ test "ed25519 batch verification" { |
| 338 | 513 | var msg2: [32]u8 = undefined; |
| 339 | 514 | crypto.random.bytes(&msg1); |
| 340 | 515 | crypto.random.bytes(&msg2); |
| 341 | | const sig1 = try Ed25519.sign(&msg1, key_pair, null); |
| 342 | | const sig2 = try Ed25519.sign(&msg2, key_pair, null); |
| 516 | const sig1 = try key_pair.sign(&msg1, null); |
| 517 | const sig2 = try key_pair.sign(&msg2, null); |
| 343 | 518 | var signature_batch = [_]Ed25519.BatchElement{ |
| 344 | 519 | Ed25519.BatchElement{ |
| 345 | 520 | .sig = sig1, |
| ... | ... | @@ -355,9 +530,7 @@ test "ed25519 batch verification" { |
| 355 | 530 | try Ed25519.verifyBatch(2, signature_batch); |
| 356 | 531 | |
| 357 | 532 | signature_batch[1].sig = sig1; |
| 358 | | // TODO https://github.com/ziglang/zig/issues/12240 |
| 359 | | const sig_len = signature_batch.len; |
| 360 | | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(sig_len, signature_batch)); |
| 533 | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(signature_batch.len, signature_batch)); |
| 361 | 534 | } |
| 362 | 535 | } |
| 363 | 536 | |
| ... | ... | @@ -446,20 +619,25 @@ test "ed25519 test vectors" { |
| 446 | 619 | for (entries) |entry| { |
| 447 | 620 | var msg: [entry.msg_hex.len / 2]u8 = undefined; |
| 448 | 621 | _ = try fmt.hexToBytes(&msg, entry.msg_hex); |
| 449 | | var public_key: [32]u8 = undefined; |
| 450 | | _ = try fmt.hexToBytes(&public_key, entry.public_key_hex); |
| 451 | | var sig: [64]u8 = undefined; |
| 452 | | _ = try fmt.hexToBytes(&sig, entry.sig_hex); |
| 622 | var public_key_bytes: [32]u8 = undefined; |
| 623 | _ = try fmt.hexToBytes(&public_key_bytes, entry.public_key_hex); |
| 624 | const public_key = Ed25519.PublicKey.fromBytes(public_key_bytes) catch |err| { |
| 625 | try std.testing.expectEqual(entry.expected.?, err); |
| 626 | continue; |
| 627 | }; |
| 628 | var sig_bytes: [64]u8 = undefined; |
| 629 | _ = try fmt.hexToBytes(&sig_bytes, entry.sig_hex); |
| 630 | const sig = Ed25519.Signature.fromBytes(sig_bytes); |
| 453 | 631 | if (entry.expected) |error_type| { |
| 454 | | try std.testing.expectError(error_type, Ed25519.verify(sig, &msg, public_key)); |
| 632 | try std.testing.expectError(error_type, sig.verify(&msg, public_key)); |
| 455 | 633 | } else { |
| 456 | | try Ed25519.verify(sig, &msg, public_key); |
| 634 | try sig.verify(&msg, public_key); |
| 457 | 635 | } |
| 458 | 636 | } |
| 459 | 637 | } |
| 460 | 638 | |
| 461 | 639 | test "ed25519 with blind keys" { |
| 462 | | const BlindKeySignatures = Ed25519.BlindKeySignatures; |
| 640 | const BlindKeyPair = Ed25519.key_blinding.BlindKeyPair; |
| 463 | 641 | |
| 464 | 642 | // Create a standard Ed25519 key pair |
| 465 | 643 | const kp = try Ed25519.KeyPair.create(null); |
| ... | ... | @@ -469,14 +647,30 @@ test "ed25519 with blind keys" { |
| 469 | 647 | crypto.random.bytes(&blind); |
| 470 | 648 | |
| 471 | 649 | // Blind the key pair |
| 472 | | const blind_kp = try BlindKeySignatures.blind(kp, blind, "ctx"); |
| 650 | const blind_kp = try BlindKeyPair.init(kp, blind, "ctx"); |
| 473 | 651 | |
| 474 | 652 | // Sign a message and check that it can be verified with the blind public key |
| 475 | 653 | const msg = "test"; |
| 476 | | const sig = try BlindKeySignatures.sign(msg, blind_kp, null); |
| 477 | | try Ed25519.verify(sig, msg, blind_kp.blind_public_key); |
| 654 | const sig = try blind_kp.sign(msg, null); |
| 655 | try sig.verify(msg, blind_kp.blind_public_key.key); |
| 478 | 656 | |
| 479 | 657 | // Unblind the public key |
| 480 | | const pk = try BlindKeySignatures.unblindPublicKey(blind_kp.blind_public_key, blind, "ctx"); |
| 481 | | try std.testing.expectEqualSlices(u8, &pk, &kp.public_key); |
| 658 | const pk = try blind_kp.blind_public_key.unblind(blind, "ctx"); |
| 659 | try std.testing.expectEqualSlices(u8, &pk.toBytes(), &kp.public_key.toBytes()); |
| 660 | } |
| 661 | |
| 662 | test "ed25519 signatures with streaming" { |
| 663 | const kp = try Ed25519.KeyPair.create(null); |
| 664 | |
| 665 | var signer = try kp.signer(null); |
| 666 | signer.update("mes"); |
| 667 | signer.update("sage"); |
| 668 | const sig = signer.finalize(); |
| 669 | |
| 670 | try sig.verify("message", kp.public_key); |
| 671 | |
| 672 | var verifier = try sig.verifier(kp.public_key); |
| 673 | verifier.update("mess"); |
| 674 | verifier.update("age"); |
| 675 | try verifier.verify(); |
| 482 | 676 | } |