der_length_integer.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /* LibTomCrypt, modular cryptographic library -- Tom St Denis
  2. *
  3. * LibTomCrypt is a library that provides various cryptographic
  4. * algorithms in a highly modular and flexible manner.
  5. *
  6. * The library is free for all purposes without any express
  7. * guarantee it works.
  8. *
  9. * Tom St Denis, [email protected], http://libtomcrypt.org
  10. */
  11. #include "mycrypt.h"
  12. /* Gets length of DER encoding of num */
  13. int der_length_integer(mp_int *num, unsigned long *outlen)
  14. {
  15. unsigned long z, len;
  16. int leading_zero;
  17. _ARGCHK(num != NULL);
  18. _ARGCHK(outlen != NULL);
  19. /* we only need a leading zero if the msb of the first byte is one */
  20. if ((mp_count_bits(num) & 7) == 7 || mp_iszero(num) == MP_YES) {
  21. leading_zero = 1;
  22. } else {
  23. leading_zero = 0;
  24. }
  25. /* size for bignum */
  26. z = len = leading_zero + mp_unsigned_bin_size(num);
  27. /* we need a 0x02 */
  28. ++len;
  29. /* now we need a length */
  30. if (z < 128) {
  31. /* short form */
  32. ++len;
  33. } else {
  34. /* long form (relies on z != 0) */
  35. ++len;
  36. while (z) {
  37. ++len;
  38. z >>= 8;
  39. }
  40. }
  41. *outlen = len;
  42. return CRYPT_OK;
  43. }