rsa_x931.c 2.6 KB

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