Skip to content

Commit e836af5

Browse files
committed
re-factor tweetnacl_crypto_hash[_ctx]()
@etienne-lms remarked in [0] that the stack usage could be minimized by using `hash_memory_multi()` instead of copying the data, so let's do that. [0] OP-TEE/optee_os#5486 (comment) Signed-off-by: Steffen Jaeckel <s@jaeckel.eu>
1 parent 288088c commit e836af5

File tree

1 file changed

+8
-25
lines changed

1 file changed

+8
-25
lines changed

src/pk/ec25519/tweetnacl.c

Lines changed: 8 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -221,39 +221,22 @@ int tweetnacl_crypto_scalarmult_base(u8 *q,const u8 *n)
221221
return tweetnacl_crypto_scalarmult(q,n,nine);
222222
}
223223

224-
static int tweetnacl_crypto_hash(u8 *out,const u8 *m,u64 n)
224+
static LTC_INLINE int tweetnacl_crypto_hash_ctx(u8 *out,const u8 *m,u64 n,const u8 *ctx,u32 cs)
225225
{
226-
unsigned long len;
227-
int err, hash_idx;
226+
unsigned long len = 64;
227+
int hash_idx = find_hash("sha512");
228228

229229
if (n > ULONG_MAX) return CRYPT_OVERFLOW;
230230

231-
hash_idx = find_hash("sha512");
232-
len = 64;
233-
if ((err = hash_memory(hash_idx, m, n, out, &len)) != CRYPT_OK) return err;
231+
if(cs == 0)
232+
return hash_memory(hash_idx, m, n, out, &len);
234233

235-
return 0;
234+
return hash_memory_multi(hash_idx, out, &len, ctx, cs, m, n, LTC_NULL);
236235
}
237236

238-
static int tweetnacl_crypto_hash_ctx(u8 *out,const u8 *m,u64 n,const u8 *ctx,u32 cs)
237+
static LTC_INLINE int tweetnacl_crypto_hash(u8 *out,const u8 *m,u64 n)
239238
{
240-
unsigned long len;
241-
int err;
242-
u8 buf[512];
243-
244-
if(cs == 0)
245-
return tweetnacl_crypto_hash(out,m,n);
246-
247-
len = n + cs;
248-
if (len > 512) return CRYPT_HASH_OVERFLOW;
249-
250-
XMEMCPY(buf,ctx,cs);
251-
XMEMCPY(buf+cs,m,n);
252-
253-
err = tweetnacl_crypto_hash(out,buf,len);
254-
zeromem(buf, len);
255-
256-
return err;
239+
return tweetnacl_crypto_hash_ctx(out, m, n, NULL, 0);
257240
}
258241

259242
sv add(gf p[4],gf q[4])

0 commit comments

Comments
 (0)