sm2_key_sharetest.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the License); you may
  5. * not use this file except in compliance with the License.
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. */
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <stdlib.h>
  12. #include <stdint.h>
  13. #include <gmssl/sm2.h>
  14. #include <gmssl/sm2_key_share.h>
  15. #include <gmssl/mem.h>
  16. #include <gmssl/error.h>
  17. static int test_sm2_key_share_args(size_t k, size_t n)
  18. {
  19. SM2_KEY key;
  20. SM2_KEY key_;
  21. SM2_KEY_SHARE shares[SM2_KEY_MAX_SHARES];
  22. if (sm2_key_generate(&key) != 1) {
  23. error_print();
  24. return -1;
  25. }
  26. if (sm2_key_split(&key, k, n, shares) != 1) {
  27. error_print();
  28. return -1;
  29. }
  30. // recover from 0 .. k
  31. if (sm2_key_recover(&key_, shares, k) != 1) {
  32. error_print();
  33. return -1;
  34. }
  35. if (memcmp(&key_, &key, sizeof(SM2_KEY)) != 0) {
  36. error_print();
  37. return -1;
  38. }
  39. // recover from n-k .. n
  40. memset(&key_, 0, sizeof(key_));
  41. if (sm2_key_recover(&key_, shares + n - k, k) != 1) {
  42. error_print();
  43. return -1;
  44. }
  45. if (memcmp(&key_, &key, sizeof(SM2_KEY)) != 0) {
  46. error_print();
  47. return -1;
  48. }
  49. return 1;
  50. }
  51. static int test_sm2_key_share(void)
  52. {
  53. if (test_sm2_key_share_args(1, 1) != 1) { error_print(); return -1; }
  54. if (test_sm2_key_share_args(1, 3) != 1) { error_print(); return -1; }
  55. if (test_sm2_key_share_args(2, 3) != 1) { error_print(); return -1; }
  56. if (test_sm2_key_share_args(3, 5) != 1) { error_print(); return -1; }
  57. if (test_sm2_key_share_args(4, 5) != 1) { error_print(); return -1; }
  58. if (test_sm2_key_share_args(5, 5) != 1) { error_print(); return -1; }
  59. if (test_sm2_key_share_args(11, 12) != 1) { error_print(); return -1; }
  60. if (test_sm2_key_share_args(12, 12) != 1) { error_print(); return -1; }
  61. return 1;
  62. }
  63. static int test_sm2_key_share_file(void)
  64. {
  65. SM2_KEY key;
  66. SM2_KEY_SHARE shares[SM2_KEY_MAX_SHARES];
  67. if (sm2_key_generate(&key) != 1) {
  68. error_print();
  69. return -1;
  70. }
  71. if (sm2_key_split(&key, 2, 3, shares) != 1) {
  72. error_print();
  73. return -1;
  74. }
  75. if (sm2_key_share_encrypt_to_file(&shares[0], "123456", "sm2key") != 1
  76. || sm2_key_share_encrypt_to_file(&shares[1], "123456", "sm2key") != 1
  77. || sm2_key_share_encrypt_to_file(&shares[2], "123456", "sm2key") != 1) {
  78. error_print();
  79. return -1;
  80. }
  81. return 1;
  82. }
  83. int main(void)
  84. {
  85. return 0;
  86. }