2
0

rsa_saos.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
  40. return 0;
  41. }
  42. p = s;
  43. i2d_ASN1_OCTET_STRING(&sig, &p);
  44. i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING);
  45. if (i <= 0)
  46. ret = 0;
  47. else
  48. *siglen = i;
  49. OPENSSL_clear_free(s, (unsigned int)j + 1);
  50. return ret;
  51. }
  52. int RSA_verify_ASN1_OCTET_STRING(int dtype,
  53. const unsigned char *m,
  54. unsigned int m_len, unsigned char *sigbuf,
  55. unsigned int siglen, RSA *rsa)
  56. {
  57. int i, ret = 0;
  58. unsigned char *s;
  59. const unsigned char *p;
  60. ASN1_OCTET_STRING *sig = NULL;
  61. if (siglen != (unsigned int)RSA_size(rsa)) {
  62. ERR_raise(ERR_LIB_RSA, RSA_R_WRONG_SIGNATURE_LENGTH);
  63. return 0;
  64. }
  65. s = OPENSSL_malloc((unsigned int)siglen);
  66. if (s == NULL) {
  67. ERR_raise(ERR_LIB_RSA, ERR_R_MALLOC_FAILURE);
  68. goto err;
  69. }
  70. i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING);
  71. if (i <= 0)
  72. goto err;
  73. p = s;
  74. sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i);
  75. if (sig == NULL)
  76. goto err;
  77. if (((unsigned int)sig->length != m_len) ||
  78. (memcmp(m, sig->data, m_len) != 0)) {
  79. ERR_raise(ERR_LIB_RSA, RSA_R_BAD_SIGNATURE);
  80. } else {
  81. ret = 1;
  82. }
  83. err:
  84. ASN1_OCTET_STRING_free(sig);
  85. OPENSSL_clear_free(s, (unsigned int)siglen);
  86. return ret;
  87. }