summaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
authorjsing <>2023-05-09 05:15:55 +0000
committerjsing <>2023-05-09 05:15:55 +0000
commitbddde9f4a7b728245a440b7da9afc22565f90e1f (patch)
treee69f633337f2b27a9aa779f59fe96171150b6ca8 /src/lib
parent0397bb0dc2794656636489f8fb435e461785f245 (diff)
downloadopenbsd-bddde9f4a7b728245a440b7da9afc22565f90e1f.tar.gz
openbsd-bddde9f4a7b728245a440b7da9afc22565f90e1f.tar.bz2
openbsd-bddde9f4a7b728245a440b7da9afc22565f90e1f.zip
Rewrite BN_bn2hex() using CBB/CBS.
ok tb@
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/libcrypto/bn/bn_convert.c60
1 files changed, 35 insertions, 25 deletions
diff --git a/src/lib/libcrypto/bn/bn_convert.c b/src/lib/libcrypto/bn/bn_convert.c
index 673db093d8..65834ffd1e 100644
--- a/src/lib/libcrypto/bn/bn_convert.c
+++ b/src/lib/libcrypto/bn/bn_convert.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: bn_convert.c,v 1.7 2023/05/09 05:12:49 jsing Exp $ */ 1/* $OpenBSD: bn_convert.c,v 1.8 2023/05/09 05:15:55 jsing Exp $ */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) 2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved. 3 * All rights reserved.
4 * 4 *
@@ -418,39 +418,49 @@ err:
418 return (0); 418 return (0);
419} 419}
420 420
421/* Must 'free' the returned data */
422char * 421char *
423BN_bn2hex(const BIGNUM *a) 422BN_bn2hex(const BIGNUM *bn)
424{ 423{
425 int i, j, v, z = 0; 424 int started = 0;
426 char *buf; 425 uint8_t *s = NULL;
427 char *p; 426 size_t s_len;
427 BN_ULONG v, w;
428 int i, j;
429 CBB cbb;
428 430
429 buf = malloc(BN_is_negative(a) + a->top * BN_BYTES * 2 + 2); 431 if (!CBB_init(&cbb, 0))
430 if (buf == NULL) {
431 BNerror(ERR_R_MALLOC_FAILURE);
432 goto err; 432 goto err;
433
434 if (BN_is_negative(bn)) {
435 if (!CBB_add_u8(&cbb, '-'))
436 goto err;
433 } 437 }
434 p = buf; 438 if (BN_is_zero(bn)) {
435 if (BN_is_negative(a)) 439 if (!CBB_add_u8(&cbb, '0'))
436 *p++ = '-'; 440 goto err;
437 if (BN_is_zero(a)) 441 }
438 *p++ = '0'; 442 for (i = bn->top - 1; i >= 0; i--) {
439 for (i = a->top - 1; i >=0; i--) { 443 w = bn->d[i];
440 for (j = BN_BITS2 - 8; j >= 0; j -= 8) { 444 for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
441 /* strip leading zeros */ 445 v = (w >> j) & 0xff;
442 v = ((int)(a->d[i] >> (long)j)) & 0xff; 446 if (!started && v == 0)
443 if (z || (v != 0)) { 447 continue;
444 *p++ = hex_digits[v >> 4]; 448 if (!CBB_add_u8(&cbb, hex_digits[v >> 4]))
445 *p++ = hex_digits[v & 0x0f]; 449 goto err;
446 z = 1; 450 if (!CBB_add_u8(&cbb, hex_digits[v & 0xf]))
447 } 451 goto err;
452 started = 1;
448 } 453 }
449 } 454 }
450 *p = '\0'; 455 if (!CBB_add_u8(&cbb, '\0'))
456 goto err;
457 if (!CBB_finish(&cbb, &s, &s_len))
458 goto err;
451 459
452err: 460 err:
453 return (buf); 461 CBB_cleanup(&cbb);
462
463 return s;
454} 464}
455 465
456int 466int