2
0

rsa_x931.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /*
  2. * Copyright 2005-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. int RSA_padding_add_X931(unsigned char *to, int tlen,
  20. const unsigned char *from, int flen)
  21. {
  22. int j;
  23. unsigned char *p;
  24. /*
  25. * Absolute minimum amount of padding is 1 header nibble, 1 padding
  26. * nibble and 2 trailer bytes: but 1 hash if is already in 'from'.
  27. */
  28. j = tlen - flen - 2;
  29. if (j < 0) {
  30. ERR_raise(ERR_LIB_RSA, RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
  31. return -1;
  32. }
  33. p = (unsigned char *)to;
  34. /* If no padding start and end nibbles are in one byte */
  35. if (j == 0) {
  36. *p++ = 0x6A;
  37. } else {
  38. *p++ = 0x6B;
  39. if (j > 1) {
  40. memset(p, 0xBB, j - 1);
  41. p += j - 1;
  42. }
  43. *p++ = 0xBA;
  44. }
  45. memcpy(p, from, (unsigned int)flen);
  46. p += flen;
  47. *p = 0xCC;
  48. return 1;
  49. }
  50. int RSA_padding_check_X931(unsigned char *to, int tlen,
  51. const unsigned char *from, int flen, int num)
  52. {
  53. int i = 0, j;
  54. const unsigned char *p;
  55. p = from;
  56. if ((num != flen) || ((*p != 0x6A) && (*p != 0x6B))) {
  57. ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_HEADER);
  58. return -1;
  59. }
  60. if (*p++ == 0x6B) {
  61. j = flen - 3;
  62. for (i = 0; i < j; i++) {
  63. unsigned char c = *p++;
  64. if (c == 0xBA)
  65. break;
  66. if (c != 0xBB) {
  67. ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
  68. return -1;
  69. }
  70. }
  71. j -= i;
  72. if (i == 0) {
  73. ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_PADDING);
  74. return -1;
  75. }
  76. } else {
  77. j = flen - 2;
  78. }
  79. if (p[j] != 0xCC) {
  80. ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER);
  81. return -1;
  82. }
  83. memcpy(to, p, (unsigned int)j);
  84. return j;
  85. }
  86. /* Translate between X931 hash ids and NIDs */
  87. int RSA_X931_hash_id(int nid)
  88. {
  89. switch (nid) {
  90. case NID_sha1:
  91. return 0x33;
  92. case NID_sha256:
  93. return 0x34;
  94. case NID_sha384:
  95. return 0x36;
  96. case NID_sha512:
  97. return 0x35;
  98. }
  99. return -1;
  100. }