rsa_saos.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (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. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include <openssl/bn.h>
  12. #include <openssl/rsa.h>
  13. #include <openssl/objects.h>
  14. #include <openssl/x509.h>
  15. int RSA_sign_ASN1_OCTET_STRING(int type,
  16. const unsigned char *m, unsigned int m_len,
  17. unsigned char *sigret, unsigned int *siglen,
  18. RSA *rsa)
  19. {
  20. ASN1_OCTET_STRING sig;
  21. int i, j, ret = 1;
  22. unsigned char *p, *s;
  23. sig.type = V_ASN1_OCTET_STRING;
  24. sig.length = m_len;
  25. sig.data = (unsigned char *)m;
  26. i = i2d_ASN1_OCTET_STRING(&sig, NULL);
  27. j = RSA_size(rsa);
  28. if (i > (j - RSA_PKCS1_PADDING_SIZE)) {
  29. RSAerr(RSA_F_RSA_SIGN_ASN1_OCTET_STRING,
  30. RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
  31. return 0;
  32. }
  33. s = OPENSSL_malloc((unsigned int)j + 1);
  34. if (s == NULL) {
  35. RSAerr(RSA_F_RSA_SIGN_ASN1_OCTET_STRING, ERR_R_MALLOC_FAILURE);
  36. return 0;
  37. }
  38. p = s;
  39. i2d_ASN1_OCTET_STRING(&sig, &p);
  40. i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING);
  41. if (i <= 0)
  42. ret = 0;
  43. else
  44. *siglen = i;
  45. OPENSSL_clear_free(s, (unsigned int)j + 1);
  46. return ret;
  47. }
  48. int RSA_verify_ASN1_OCTET_STRING(int dtype,
  49. const unsigned char *m,
  50. unsigned int m_len, unsigned char *sigbuf,
  51. unsigned int siglen, RSA *rsa)
  52. {
  53. int i, ret = 0;
  54. unsigned char *s;
  55. const unsigned char *p;
  56. ASN1_OCTET_STRING *sig = NULL;
  57. if (siglen != (unsigned int)RSA_size(rsa)) {
  58. RSAerr(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING,
  59. RSA_R_WRONG_SIGNATURE_LENGTH);
  60. return 0;
  61. }
  62. s = OPENSSL_malloc((unsigned int)siglen);
  63. if (s == NULL) {
  64. RSAerr(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING, ERR_R_MALLOC_FAILURE);
  65. goto err;
  66. }
  67. i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING);
  68. if (i <= 0)
  69. goto err;
  70. p = s;
  71. sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i);
  72. if (sig == NULL)
  73. goto err;
  74. if (((unsigned int)sig->length != m_len) ||
  75. (memcmp(m, sig->data, m_len) != 0)) {
  76. RSAerr(RSA_F_RSA_VERIFY_ASN1_OCTET_STRING, RSA_R_BAD_SIGNATURE);
  77. } else {
  78. ret = 1;
  79. }
  80. err:
  81. ASN1_OCTET_STRING_free(sig);
  82. OPENSSL_clear_free(s, (unsigned int)siglen);
  83. return ret;
  84. }