rsa_saos.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. /*
  10. * RSA low level APIs are deprecated for public use, but still ok for
  11. * internal use.
  12. */
  13. #include "internal/deprecated.h"
  14. #include <stdio.h>
  15. #include "internal/cryptlib.h"
  16. #include <openssl/bn.h>
  17. #include <openssl/rsa.h>
  18. #include <openssl/objects.h>
  19. #include <openssl/x509.h>
  20. int RSA_sign_ASN1_OCTET_STRING(int type,
  21. const unsigned char *m, unsigned int m_len,
  22. unsigned char *sigret, unsigned int *siglen,
  23. RSA *rsa)
  24. {
  25. ASN1_OCTET_STRING sig;
  26. int i, j, ret = 1;
  27. unsigned char *p, *s;
  28. sig.type = V_ASN1_OCTET_STRING;
  29. sig.length = m_len;
  30. sig.data = (unsigned char *)m;
  31. i = i2d_ASN1_OCTET_STRING(&sig, NULL);
  32. j = RSA_size(rsa);
  33. if (i > (j - RSA_PKCS1_PADDING_SIZE)) {
  34. ERR_raise(ERR_LIB_RSA, RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
  35. return 0;
  36. }
  37. s = OPENSSL_malloc((unsigned int)j + 1);
  38. if (s == NULL)
  39. return 0;
  40. p = s;
  41. i2d_ASN1_OCTET_STRING(&sig, &p);
  42. i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING);
  43. if (i <= 0)
  44. ret = 0;
  45. else
  46. *siglen = i;
  47. OPENSSL_clear_free(s, (unsigned int)j + 1);
  48. return ret;
  49. }
  50. int RSA_verify_ASN1_OCTET_STRING(int dtype,
  51. const unsigned char *m,
  52. unsigned int m_len, unsigned char *sigbuf,
  53. unsigned int siglen, RSA *rsa)
  54. {
  55. int i, ret = 0;
  56. unsigned char *s;
  57. const unsigned char *p;
  58. ASN1_OCTET_STRING *sig = NULL;
  59. if (siglen != (unsigned int)RSA_size(rsa)) {
  60. ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH);
  61. return 0;
  62. }
  63. s = OPENSSL_malloc((unsigned int)siglen);
  64. if (s == NULL)
  65. goto err;
  66. i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING);
  67. if (i <= 0)
  68. goto err;
  69. p = s;
  70. sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i);
  71. if (sig == NULL)
  72. goto err;
  73. if (((unsigned int)sig->length != m_len) ||
  74. (memcmp(m, sig->data, m_len) != 0)) {
  75. ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE);
  76. } else {
  77. ret = 1;
  78. }
  79. err:
  80. ASN1_OCTET_STRING_free(sig);
  81. OPENSSL_clear_free(s, (unsigned int)siglen);
  82. return ret;
  83. }