pkcs_1_v15_sa_encode.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. /* PKCS #1 v1.5 Signature Padding -- Tom St Denis */
  13. #ifdef PKCS_1
  14. int pkcs_1_v15_sa_encode(const unsigned char *msghash, unsigned long msghashlen,
  15. int hash_idx, unsigned long modulus_bitlen,
  16. unsigned char *out, unsigned long *outlen)
  17. {
  18. unsigned long derlen, modulus_bytelen, x, y;
  19. int err;
  20. _ARGCHK(msghash != NULL)
  21. _ARGCHK(out != NULL);
  22. _ARGCHK(outlen != NULL);
  23. if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
  24. return err;
  25. }
  26. /* hack, to detect any hash without a DER OID */
  27. if (hash_descriptor[hash_idx].DERlen == 0) {
  28. return CRYPT_INVALID_ARG;
  29. }
  30. /* get modulus len */
  31. modulus_bytelen = (modulus_bitlen>>3) + (modulus_bitlen & 7 ? 1 : 0);
  32. /* get der len ok? Forgive my lame German accent.... */
  33. derlen = hash_descriptor[hash_idx].DERlen;
  34. /* valid sizes? */
  35. if (msghashlen + 3 + derlen > modulus_bytelen) {
  36. return CRYPT_PK_INVALID_SIZE;
  37. }
  38. if (*outlen < modulus_bytelen) {
  39. return CRYPT_BUFFER_OVERFLOW;
  40. }
  41. /* packet is 0x00 0x01 PS 0x00 T, where PS == 0xFF repeated modulus_bytelen - 3 - derlen - msghashlen times, T == DER || hash */
  42. x = 0;
  43. out[x++] = 0x00;
  44. out[x++] = 0x01;
  45. for (y = 0; y < (modulus_bytelen - 3 - derlen - msghashlen); y++) {
  46. out[x++] = 0xFF;
  47. }
  48. out[x++] = 0x00;
  49. for (y = 0; y < derlen; y++) {
  50. out[x++] = hash_descriptor[hash_idx].DER[y];
  51. }
  52. for (y = 0; y < msghashlen; y++) {
  53. out[x++] = msghash[y];
  54. }
  55. *outlen = modulus_bytelen;
  56. return CRYPT_OK;
  57. }
  58. #endif /* PKCS_1 */