summaryrefslogtreecommitdiff
path: root/bufaux.c
diff options
context:
space:
mode:
Diffstat (limited to 'bufaux.c')
-rw-r--r--bufaux.c76
1 files changed, 75 insertions, 1 deletions
diff --git a/bufaux.c b/bufaux.c
index de5b3ca1a..9401fe1d0 100644
--- a/bufaux.c
+++ b/bufaux.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: bufaux.c,v 1.52 2013/07/12 00:19:58 djm Exp $ */ 1/* $OpenBSD: bufaux.c,v 1.54 2014/01/12 08:13:13 djm Exp $ */
2/* 2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -45,6 +45,7 @@
45 45
46#include <string.h> 46#include <string.h>
47#include <stdarg.h> 47#include <stdarg.h>
48#include <stdlib.h>
48 49
49#include "xmalloc.h" 50#include "xmalloc.h"
50#include "buffer.h" 51#include "buffer.h"
@@ -314,3 +315,76 @@ buffer_put_char(Buffer *buffer, int value)
314 315
315 buffer_append(buffer, &ch, 1); 316 buffer_append(buffer, &ch, 1);
316} 317}
318
319/* Pseudo bignum functions */
320
321void *
322buffer_get_bignum2_as_string_ret(Buffer *buffer, u_int *length_ptr)
323{
324 u_int len;
325 u_char *bin, *p, *ret;
326
327 if ((p = bin = buffer_get_string_ret(buffer, &len)) == NULL) {
328 error("%s: invalid bignum", __func__);
329 return NULL;
330 }
331
332 if (len > 0 && (bin[0] & 0x80)) {
333 error("%s: negative numbers not supported", __func__);
334 free(bin);
335 return NULL;
336 }
337 if (len > 8 * 1024) {
338 error("%s: cannot handle BN of size %d", __func__, len);
339 free(bin);
340 return NULL;
341 }
342 /* Skip zero prefix on numbers with the MSB set */
343 if (len > 1 && bin[0] == 0x00 && (bin[1] & 0x80) != 0) {
344 p++;
345 len--;
346 }
347 ret = xmalloc(len);
348 memcpy(ret, p, len);
349 memset(p, '\0', len);
350 free(bin);
351 return ret;
352}
353
354void *
355buffer_get_bignum2_as_string(Buffer *buffer, u_int *l)
356{
357 void *ret = buffer_get_bignum2_as_string_ret(buffer, l);
358
359 if (ret == NULL)
360 fatal("%s: buffer error", __func__);
361 return ret;
362}
363
364/*
365 * Stores a string using the bignum encoding rules (\0 pad if MSB set).
366 */
367void
368buffer_put_bignum2_from_string(Buffer *buffer, const u_char *s, u_int l)
369{
370 u_char *buf, *p;
371 int pad = 0;
372
373 if (l > 8 * 1024)
374 fatal("%s: length %u too long", __func__, l);
375 p = buf = xmalloc(l + 1);
376 /*
377 * If most significant bit is set then prepend a zero byte to
378 * avoid interpretation as a negative number.
379 */
380 if (l > 0 && (s[0] & 0x80) != 0) {
381 *p++ = '\0';
382 pad = 1;
383 }
384 memcpy(p, s, l);
385 buffer_put_string(buffer, buf, l + pad);
386 memset(buf, '\0', l + pad);
387 free(buf);
388}
389
390