| ... | @@ -16,27 +16,227 @@ const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; | ... | @@ -16,27 +16,227 @@ const WeakPublicKeyError = crypto.errors.WeakPublicKeyError; |
| 16 | /// Ed25519 (EdDSA) signatures. | 16 | /// Ed25519 (EdDSA) signatures. |
| 17 | pub const Ed25519 = struct { | 17 | pub const Ed25519 = struct { |
| 18 | /// The underlying elliptic curve. | 18 | /// The underlying elliptic curve. |
| 19 | pub const Curve = @import("edwards25519.zig").Edwards25519; | 19 | pub const Curve = std.crypto.ecc.Edwards25519; |
| 20 | /// Length (in bytes) of a seed required to create a key pair. | 20 | |
| 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; | | |
| 28 | /// Length (in bytes) of optional random bytes, for non-deterministic signatures. | 21 | /// Length (in bytes) of optional random bytes, for non-deterministic signatures. |
| 29 | pub const noise_length = 32; | 22 | pub const noise_length = 32; |
| 30 | | 23 | |
| 31 | const CompressedScalar = Curve.scalar.CompressedScalar; | 24 | const CompressedScalar = Curve.scalar.CompressedScalar; |
| 32 | const Scalar = Curve.scalar.Scalar; | 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 | /// An Ed25519 key pair. | 231 | /// An Ed25519 key pair. |
| 35 | pub const KeyPair = struct { | 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 | /// Public part. | 236 | /// Public part. |
| 37 | public_key: [public_length]u8, | 237 | public_key: PublicKey, |
| 38 | /// Secret part. What we expose as a secret key is, under the hood, the concatenation of the seed and the public key. | 238 | /// Secret scalar. |
| 39 | secret_key: [secret_length]u8, | 239 | secret_key: SecretKey, |
| 40 | | 240 | |
| 41 | /// Derive a key pair from an optional secret seed. | 241 | /// Derive a key pair from an optional secret seed. |
| 42 | /// | 242 | /// |
| ... | @@ -56,120 +256,101 @@ pub const Ed25519 = struct { | ... | @@ -56,120 +256,101 @@ pub const Ed25519 = struct { |
| 56 | var h = Sha512.init(.{}); | 256 | var h = Sha512.init(.{}); |
| 57 | h.update(&ss); | 257 | h.update(&ss); |
| 58 | h.final(&az); | 258 | h.final(&az); |
| 59 | const p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; | 259 | const pk_p = Curve.basePoint.clampedMul(az[0..32].*) catch return error.IdentityElement; |
| 60 | var sk: [secret_length]u8 = undefined; | 260 | const pk_bytes = pk_p.toBytes(); |
| 61 | mem.copy(u8, &sk, &ss); | 261 | var sk_bytes: [SecretKey.encoded_length]u8 = undefined; |
| 62 | const pk = p.toBytes(); | 262 | mem.copy(u8, &sk_bytes, &ss); |
| 63 | mem.copy(u8, sk[seed_length..], &pk); | 263 | mem.copy(u8, sk_bytes[seed_length..], &pk_bytes); |
| 64 | | 264 | return KeyPair{ |
| 65 | return KeyPair{ .public_key = pk, .secret_key = sk }; | 265 | .public_key = PublicKey.fromBytes(pk_bytes) catch unreachable, |
| | 266 | .secret_key = try SecretKey.fromBytes(sk_bytes), |
| | 267 | }; |
| 66 | } | 268 | } |
| 67 | | 269 | |
| 68 | /// Create a KeyPair from a secret key. | 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 | return KeyPair{ | 281 | return KeyPair{ |
| | 282 | .public_key = PublicKey{ .p = pk_p }, |
| 71 | .secret_key = secret_key, | 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. | 287 | /// Sign a message using the key pair. |
| 78 | /// Having noise creates non-standard, non-deterministic signatures, | 288 | /// The noise can be null in order to create deterministic signatures. |
| 79 | /// but has been proven to increase resilience against fault attacks. | 289 | /// If deterministic signatures are not required, the noise should be randomly generated instead. |
| 80 | pub fn sign(msg: []const u8, key_pair: KeyPair, noise: ?[noise_length]u8) (IdentityElementError || WeakPublicKeyError || KeyMismatchError)![signature_length]u8 { | 290 | /// This helps defend against fault attacks. |
| 81 | const seed = key_pair.secret_key[0..seed_length]; | 291 | pub fn sign(key_pair: KeyPair, msg: []const u8, noise: ?[noise_length]u8) (IdentityElementError || NonCanonicalError || KeyMismatchError || WeakPublicKeyError)!Signature { |
| 82 | const public_key = key_pair.secret_key[seed_length..]; | 292 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 83 | if (!mem.eql(u8, public_key, &key_pair.public_key)) { | 293 | return error.KeyMismatch; |
| 84 | return error.KeyMismatch; | 294 | } |
| 85 | } | 295 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 86 | var az: [Sha512.digest_length]u8 = undefined; | 296 | return key_pair.public_key.computeNonceAndSign( |
| 87 | var h = Sha512.init(.{}); | 297 | msg, |
| 88 | h.update(seed); | 298 | noise, |
| 89 | h.final(&az); | 299 | scalar_and_prefix.scalar, |
| 90 | | 300 | &scalar_and_prefix.prefix, |
| 91 | h = Sha512.init(.{}); | 301 | ); |
| 92 | if (noise) |*z| { | | |
| 93 | h.update(z); | | |
| 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. | 304 | /// Create a Signer, that can be used for incremental signing. |
| 120 | /// Returns error.SignatureVerificationFailed is the signature verification failed. | 305 | /// Note that the signature is not deterministic. |
| 121 | pub fn verify(sig: [signature_length]u8, msg: []const u8, public_key: [public_length]u8) (SignatureVerificationError || WeakPublicKeyError || EncodingError || NonCanonicalError || IdentityElementError)!void { | 306 | /// The noise parameter, if set, should be something unique for each message, |
| 122 | const r = sig[0..32]; | 307 | /// such as a random nonce, or a counter. |
| 123 | const s = sig[32..64]; | 308 | pub fn signer(key_pair: KeyPair, noise: ?[noise_length]u8) (IdentityElementError || KeyMismatchError || NonCanonicalError || WeakPublicKeyError)!Signer { |
| 124 | try Curve.scalar.rejectNonCanonical(s.*); | 309 | if (!mem.eql(u8, &key_pair.secret_key.publicKeyBytes(), &key_pair.public_key.toBytes())) { |
| 125 | try Curve.rejectNonCanonical(public_key); | 310 | return error.KeyMismatch; |
| 126 | const a = try Curve.fromBytes(public_key); | 311 | } |
| 127 | try a.rejectIdentity(); | 312 | const scalar_and_prefix = key_pair.secret_key.scalarAndPrefix(); |
| 128 | try Curve.rejectNonCanonical(r.*); | 313 | var h = Sha512.init(.{}); |
| 129 | const expected_r = try Curve.fromBytes(r.*); | 314 | h.update(&scalar_and_prefix.prefix); |
| 130 | try expected_r.rejectIdentity(); | 315 | var noise2: [noise_length]u8 = undefined; |
| 131 | | 316 | crypto.random.bytes(&noise2); |
| 132 | var h = Sha512.init(.{}); | 317 | if (noise) |*z| { |
| 133 | h.update(r); | 318 | h.update(z); |
| 134 | h.update(&public_key); | 319 | } |
| 135 | h.update(msg); | 320 | var nonce64: [64]u8 = undefined; |
| 136 | var hram64: [Sha512.digest_length]u8 = undefined; | 321 | h.final(&nonce64); |
| 137 | h.final(&hram64); | 322 | const nonce = Curve.scalar.reduce64(nonce64); |
| 138 | const hram = Curve.scalar.reduce64(hram64); | 323 | |
| 139 | | 324 | return Signer.init(scalar_and_prefix.scalar, nonce, key_pair.public_key); |
| 140 | const sb_ah = try Curve.basePoint.mulDoubleBasePublic(s.*, a.neg(), hram); | 325 | } |
| 141 | if (expected_r.sub(sb_ah).clearCofactor().rejectIdentity()) |_| { | 326 | }; |
| 142 | return error.SignatureVerificationFailed; | | |
| 143 | } else |_| {} | | |
| 144 | } | | |
| 145 | | 327 | |
| 146 | /// A (signature, message, public_key) tuple for batch verification | 328 | /// A (signature, message, public_key) tuple for batch verification |
| 147 | pub const BatchElement = struct { | 329 | pub const BatchElement = struct { |
| 148 | sig: [signature_length]u8, | 330 | sig: Signature, |
| 149 | msg: []const u8, | 331 | msg: []const u8, |
| 150 | public_key: [public_length]u8, | 332 | public_key: PublicKey, |
| 151 | }; | 333 | }; |
| 152 | | 334 | |
| 153 | /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one | 335 | /// Verify several signatures in a single operation, much faster than verifying signatures one-by-one |
| 154 | pub fn verifyBatch(comptime count: usize, signature_batch: [count]BatchElement) (SignatureVerificationError || IdentityElementError || WeakPublicKeyError || EncodingError || NonCanonicalError)!void { | 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; | 337 | var r_batch: [count]CompressedScalar = undefined; |
| 156 | var s_batch: [count][32]u8 = undefined; | 338 | var s_batch: [count]CompressedScalar = undefined; |
| 157 | var a_batch: [count]Curve = undefined; | 339 | var a_batch: [count]Curve = undefined; |
| 158 | var expected_r_batch: [count]Curve = undefined; | 340 | var expected_r_batch: [count]Curve = undefined; |
| 159 | | 341 | |
| 160 | for (signature_batch) |signature, i| { | 342 | for (signature_batch) |signature, i| { |
| 161 | const r = signature.sig[0..32]; | 343 | const r = signature.sig.r; |
| 162 | const s = signature.sig[32..64]; | 344 | const s = signature.sig.s; |
| 163 | try Curve.scalar.rejectNonCanonical(s.*); | 345 | try Curve.scalar.rejectNonCanonical(s); |
| 164 | try Curve.rejectNonCanonical(signature.public_key); | 346 | const a = try Curve.fromBytes(signature.public_key.bytes); |
| 165 | const a = try Curve.fromBytes(signature.public_key); | | |
| 166 | try a.rejectIdentity(); | 347 | try a.rejectIdentity(); |
| 167 | try Curve.rejectNonCanonical(r.*); | 348 | try Curve.rejectNonCanonical(r); |
| 168 | const expected_r = try Curve.fromBytes(r.*); | 349 | const expected_r = try Curve.fromBytes(r); |
| 169 | try expected_r.rejectIdentity(); | 350 | try expected_r.rejectIdentity(); |
| 170 | expected_r_batch[i] = expected_r; | 351 | expected_r_batch[i] = expected_r; |
| 171 | r_batch[i] = r.*; | 352 | r_batch[i] = r; |
| 172 | s_batch[i] = s.*; | 353 | s_batch[i] = s; |
| 173 | a_batch[i] = a; | 354 | a_batch[i] = a; |
| 174 | } | 355 | } |
| 175 | | 356 | |
| ... | @@ -177,7 +358,7 @@ pub const Ed25519 = struct { | ... | @@ -177,7 +358,7 @@ pub const Ed25519 = struct { |
| 177 | for (signature_batch) |signature, i| { | 358 | for (signature_batch) |signature, i| { |
| 178 | var h = Sha512.init(.{}); | 359 | var h = Sha512.init(.{}); |
| 179 | h.update(&r_batch[i]); | 360 | h.update(&r_batch[i]); |
| 180 | h.update(&signature.public_key); | 361 | h.update(&signature.public_key.bytes); |
| 181 | h.update(signature.msg); | 362 | h.update(signature.msg); |
| 182 | var hram64: [Sha512.digest_length]u8 = undefined; | 363 | var hram64: [Sha512.digest_length]u8 = undefined; |
| 183 | h.final(&hram64); | 364 | h.final(&hram64); |
| ... | @@ -212,7 +393,7 @@ pub const Ed25519 = struct { | ... | @@ -212,7 +393,7 @@ pub const Ed25519 = struct { |
| 212 | } | 393 | } |
| 213 | | 394 | |
| 214 | /// Ed25519 signatures with key blinding. | 395 | /// Ed25519 signatures with key blinding. |
| 215 | pub const BlindKeySignatures = struct { | 396 | pub const key_blinding = struct { |
| 216 | /// Length (in bytes) of a blinding seed. | 397 | /// Length (in bytes) of a blinding seed. |
| 217 | pub const blind_seed_length = 32; | 398 | pub const blind_seed_length = 32; |
| 218 | | 399 | |
| ... | @@ -220,81 +401,69 @@ pub const Ed25519 = struct { | ... | @@ -220,81 +401,69 @@ pub const Ed25519 = struct { |
| 220 | pub const BlindSecretKey = struct { | 401 | pub const BlindSecretKey = struct { |
| 221 | prefix: [64]u8, | 402 | prefix: [64]u8, |
| 222 | blind_scalar: CompressedScalar, | 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 | /// A blind key pair. | 421 | /// A blind key pair. |
| 227 | pub const BlindKeyPair = struct { | 422 | pub const BlindKeyPair = struct { |
| 228 | blind_public_key: [public_length]u8, | 423 | blind_public_key: BlindPublicKey, |
| 229 | blind_secret_key: BlindSecretKey, | 424 | blind_secret_key: BlindSecretKey, |
| 230 | }; | | |
| 231 | | 425 | |
| 232 | /// Blind an existing key pair with a blinding seed and a context. | 426 | /// Create an blind key pair from an existing key pair, a blinding seed and a context. |
| 233 | pub fn blind(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8, ctx: []const u8) !BlindKeyPair { | 427 | pub fn init(key_pair: Ed25519.KeyPair, blind_seed: [blind_seed_length]u8, ctx: []const u8) (NonCanonicalError || IdentityElementError)!BlindKeyPair { |
| 234 | var h: [Sha512.digest_length]u8 = undefined; | 428 | var h: [Sha512.digest_length]u8 = undefined; |
| 235 | Sha512.hash(key_pair.secret_key[0..32], &h, .{}); | 429 | Sha512.hash(&key_pair.secret_key.seed(), &h, .{}); |
| 236 | Curve.scalar.clamp(h[0..32]); | 430 | Curve.scalar.clamp(h[0..32]); |
| 237 | const scalar = Curve.scalar.reduce(h[0..32].*); | 431 | const scalar = Curve.scalar.reduce(h[0..32].*); |
| 238 | | 432 | |
| 239 | const blind_h = blindCtx(blind_seed, ctx); | 433 | const blind_h = blindCtx(blind_seed, ctx); |
| 240 | const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); | 434 | const blind_factor = Curve.scalar.reduce(blind_h[0..32].*); |
| 241 | | 435 | |
| 242 | const blind_scalar = Curve.scalar.mul(scalar, blind_factor); | 436 | const blind_scalar = Curve.scalar.mul(scalar, blind_factor); |
| 243 | const blind_public_key = (Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes(); | 437 | const blind_public_key = BlindPublicKey{ |
| 244 | | 438 | .key = try PublicKey.fromBytes((Curve.basePoint.mul(blind_scalar) catch return error.IdentityElement).toBytes()), |
| 245 | var prefix: [64]u8 = undefined; | 439 | }; |
| 246 | mem.copy(u8, prefix[0..32], h[32..64]); | 440 | |
| 247 | mem.copy(u8, prefix[32..64], blind_h[32..64]); | 441 | var prefix: [64]u8 = undefined; |
| 248 | | 442 | mem.copy(u8, prefix[0..32], h[32..64]); |
| 249 | const blind_secret_key = .{ | 443 | mem.copy(u8, prefix[32..64], blind_h[32..64]); |
| 250 | .prefix = prefix, | 444 | |
| 251 | .blind_scalar = blind_scalar, | 445 | const blind_secret_key = BlindSecretKey{ |
| 252 | .blind_public_key = blind_public_key, | 446 | .prefix = prefix, |
| 253 | }; | 447 | .blind_scalar = blind_scalar, |
| 254 | return BlindKeyPair{ | 448 | .blind_public_key = blind_public_key, |
| 255 | .blind_public_key = blind_public_key, | 449 | }; |
| 256 | .blind_secret_key = blind_secret_key, | 450 | return BlindKeyPair{ |
| 257 | }; | 451 | .blind_public_key = blind_public_key, |
| 258 | } | 452 | .blind_secret_key = blind_secret_key, |
| 259 | | 453 | }; |
| 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); | | |
| 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); | 456 | /// Sign a message using a blind key pair, and optional random noise. |
| 282 | const r = try Curve.basePoint.mul(nonce); | 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; | 463 | return (try PublicKey.fromBytes(key_pair.blind_public_key.key.bytes)) |
| 285 | mem.copy(u8, sig[0..32], &r.toBytes()); | 464 | .computeNonceAndSign(msg, noise, scalar, &prefix); |
| 286 | mem.copy(u8, sig[32..], &key_pair.blind_public_key); | 465 | } |
| 287 | h = Sha512.init(.{}); | 466 | }; |
| 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 | } | | |
| 298 | | 467 | |
| 299 | /// Compute a blind context from a blinding seed and a context. | 468 | /// Compute a blind context from a blinding seed and a context. |
| 300 | fn blindCtx(blind_seed: [blind_seed_length]u8, ctx: []const u8) [Sha512.digest_length]u8 { | 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,7 +475,13 @@ pub const Ed25519 = struct { |
| 306 | hx.final(&blind_h); | 475 | hx.final(&blind_h); |
| 307 | return blind_h; | 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 | test "ed25519 key pair creation" { | 487 | test "ed25519 key pair creation" { |
| ... | @@ -314,8 +489,8 @@ test "ed25519 key pair creation" { | ... | @@ -314,8 +489,8 @@ test "ed25519 key pair creation" { |
| 314 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); | 489 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 315 | const key_pair = try Ed25519.KeyPair.create(seed); | 490 | const key_pair = try Ed25519.KeyPair.create(seed); |
| 316 | var buf: [256]u8 = undefined; | 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"); | 492 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key.toBytes())}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); |
| 318 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key)}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083"); | 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 | test "ed25519 signature" { | 496 | test "ed25519 signature" { |
| ... | @@ -323,11 +498,11 @@ test "ed25519 signature" { | ... | @@ -323,11 +498,11 @@ test "ed25519 signature" { |
| 323 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); | 498 | _ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); |
| 324 | const key_pair = try Ed25519.KeyPair.create(seed); | 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 | var buf: [128]u8 = undefined; | 502 | var buf: [128]u8 = undefined; |
| 328 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig)}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); | 503 | try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig.toBytes())}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808"); |
| 329 | try Ed25519.verify(sig, "test", key_pair.public_key); | 504 | try sig.verify("test", key_pair.public_key); |
| 330 | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verify(sig, "TEST", key_pair.public_key)); | 505 | try std.testing.expectError(error.SignatureVerificationFailed, sig.verify("TEST", key_pair.public_key)); |
| 331 | } | 506 | } |
| 332 | | 507 | |
| 333 | test "ed25519 batch verification" { | 508 | test "ed25519 batch verification" { |
| ... | @@ -338,8 +513,8 @@ test "ed25519 batch verification" { | ... | @@ -338,8 +513,8 @@ test "ed25519 batch verification" { |
| 338 | var msg2: [32]u8 = undefined; | 513 | var msg2: [32]u8 = undefined; |
| 339 | crypto.random.bytes(&msg1); | 514 | crypto.random.bytes(&msg1); |
| 340 | crypto.random.bytes(&msg2); | 515 | crypto.random.bytes(&msg2); |
| 341 | const sig1 = try Ed25519.sign(&msg1, key_pair, null); | 516 | const sig1 = try key_pair.sign(&msg1, null); |
| 342 | const sig2 = try Ed25519.sign(&msg2, key_pair, null); | 517 | const sig2 = try key_pair.sign(&msg2, null); |
| 343 | var signature_batch = [_]Ed25519.BatchElement{ | 518 | var signature_batch = [_]Ed25519.BatchElement{ |
| 344 | Ed25519.BatchElement{ | 519 | Ed25519.BatchElement{ |
| 345 | .sig = sig1, | 520 | .sig = sig1, |
| ... | @@ -355,9 +530,7 @@ test "ed25519 batch verification" { | ... | @@ -355,9 +530,7 @@ test "ed25519 batch verification" { |
| 355 | try Ed25519.verifyBatch(2, signature_batch); | 530 | try Ed25519.verifyBatch(2, signature_batch); |
| 356 | | 531 | |
| 357 | signature_batch[1].sig = sig1; | 532 | signature_batch[1].sig = sig1; |
| 358 | // TODO https://github.com/ziglang/zig/issues/12240 | 533 | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(signature_batch.len, signature_batch)); |
| 359 | const sig_len = signature_batch.len; | | |
| 360 | try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(sig_len, signature_batch)); | | |
| 361 | } | 534 | } |
| 362 | } | 535 | } |
| 363 | | 536 | |
| ... | @@ -446,20 +619,25 @@ test "ed25519 test vectors" { | ... | @@ -446,20 +619,25 @@ test "ed25519 test vectors" { |
| 446 | for (entries) |entry| { | 619 | for (entries) |entry| { |
| 447 | var msg: [entry.msg_hex.len / 2]u8 = undefined; | 620 | var msg: [entry.msg_hex.len / 2]u8 = undefined; |
| 448 | _ = try fmt.hexToBytes(&msg, entry.msg_hex); | 621 | _ = try fmt.hexToBytes(&msg, entry.msg_hex); |
| 449 | var public_key: [32]u8 = undefined; | 622 | var public_key_bytes: [32]u8 = undefined; |
| 450 | _ = try fmt.hexToBytes(&public_key, entry.public_key_hex); | 623 | _ = try fmt.hexToBytes(&public_key_bytes, entry.public_key_hex); |
| 451 | var sig: [64]u8 = undefined; | 624 | const public_key = Ed25519.PublicKey.fromBytes(public_key_bytes) catch |err| { |
| 452 | _ = try fmt.hexToBytes(&sig, entry.sig_hex); | 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 | if (entry.expected) |error_type| { | 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 | } else { | 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 | test "ed25519 with blind keys" { | 639 | test "ed25519 with blind keys" { |
| 462 | const BlindKeySignatures = Ed25519.BlindKeySignatures; | 640 | const BlindKeyPair = Ed25519.key_blinding.BlindKeyPair; |
| 463 | | 641 | |
| 464 | // Create a standard Ed25519 key pair | 642 | // Create a standard Ed25519 key pair |
| 465 | const kp = try Ed25519.KeyPair.create(null); | 643 | const kp = try Ed25519.KeyPair.create(null); |
| ... | @@ -469,14 +647,30 @@ test "ed25519 with blind keys" { | ... | @@ -469,14 +647,30 @@ test "ed25519 with blind keys" { |
| 469 | crypto.random.bytes(&blind); | 647 | crypto.random.bytes(&blind); |
| 470 | | 648 | |
| 471 | // Blind the key pair | 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 | // Sign a message and check that it can be verified with the blind public key | 652 | // Sign a message and check that it can be verified with the blind public key |
| 475 | const msg = "test"; | 653 | const msg = "test"; |
| 476 | const sig = try BlindKeySignatures.sign(msg, blind_kp, null); | 654 | const sig = try blind_kp.sign(msg, null); |
| 477 | try Ed25519.verify(sig, msg, blind_kp.blind_public_key); | 655 | try sig.verify(msg, blind_kp.blind_public_key.key); |
| 478 | | 656 | |
| 479 | // Unblind the public key | 657 | // Unblind the public key |
| 480 | const pk = try BlindKeySignatures.unblindPublicKey(blind_kp.blind_public_key, blind, "ctx"); | 658 | const pk = try blind_kp.blind_public_key.unblind(blind, "ctx"); |
| 481 | try std.testing.expectEqualSlices(u8, &pk, &kp.public_key); | 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 | } |