pkcs_1_v15_sa_decode.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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_decode(const unsigned char *msghash, unsigned long msghashlen,
  15. const unsigned char *sig, unsigned long siglen,
  16. int hash_idx, unsigned long modulus_bitlen,
  17. int *res)
  18. {
  19. unsigned long x, y, modulus_bytelen, derlen;
  20. int err;
  21. _ARGCHK(msghash != NULL);
  22. _ARGCHK(sig != NULL);
  23. _ARGCHK(res != NULL);
  24. /* default to invalid */
  25. *res = 0;
  26. /* valid hash ? */
  27. if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
  28. return err;
  29. }
  30. /* get derlen */
  31. derlen = hash_descriptor[hash_idx].DERlen;
  32. /* get modulus len */
  33. modulus_bytelen = (modulus_bitlen>>3) + (modulus_bitlen & 7 ? 1 : 0);
  34. /* valid sizes? */
  35. if ((msghashlen + 3 + derlen > modulus_bytelen) || (siglen != modulus_bytelen)) {
  36. return CRYPT_PK_INVALID_SIZE;
  37. }
  38. /* packet is 0x00 0x01 PS 0x00 T, where PS == 0xFF repeated modulus_bytelen - 3 - derlen - msghashlen times, T == DER || hash */
  39. x = 0;
  40. if (sig[x++] != 0x00 || sig[x++] != 0x01) {
  41. return CRYPT_OK;
  42. }
  43. /* now follows (modulus_bytelen - 3 - derlen - msghashlen) 0xFF bytes */
  44. for (y = 0; y < (modulus_bytelen - 3 - derlen - msghashlen); y++) {
  45. if (sig[x++] != 0xFF) {
  46. return CRYPT_OK;
  47. }
  48. }
  49. if (sig[x++] != 0x00) {
  50. return CRYPT_OK;
  51. }
  52. for (y = 0; y < derlen; y++) {
  53. if (sig[x++] != hash_descriptor[hash_idx].DER[y]) {
  54. return CRYPT_OK;
  55. }
  56. }
  57. if (memcmp(msghash, sig+x, msghashlen) == 0) {
  58. *res = 1;
  59. }
  60. return CRYPT_OK;
  61. }
  62. #endif