2
0

sm4_internal_test.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright 2017 Ribose Inc. All Rights Reserved.
  4. *
  5. * Licensed under the OpenSSL license (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. /*
  11. * Internal tests for the SM4 module.
  12. */
  13. #include <string.h>
  14. #include <openssl/opensslconf.h>
  15. #include "testutil.h"
  16. #ifndef OPENSSL_NO_SM4
  17. # include "internal/sm4.h"
  18. static int test_sm4_ecb(void)
  19. {
  20. static const uint8_t k[SM4_BLOCK_SIZE] = {
  21. 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
  22. 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10
  23. };
  24. static const uint8_t input[SM4_BLOCK_SIZE] = {
  25. 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
  26. 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10
  27. };
  28. /*
  29. * This test vector comes from Example 1 of GB/T 32907-2016,
  30. * and described in Internet Draft draft-ribose-cfrg-sm4-02.
  31. */
  32. static const uint8_t expected[SM4_BLOCK_SIZE] = {
  33. 0x68, 0x1e, 0xdf, 0x34, 0xd2, 0x06, 0x96, 0x5e,
  34. 0x86, 0xb3, 0xe9, 0x4f, 0x53, 0x6e, 0x42, 0x46
  35. };
  36. /*
  37. * This test vector comes from Example 2 from GB/T 32907-2016,
  38. * and described in Internet Draft draft-ribose-cfrg-sm4-02.
  39. * After 1,000,000 iterations.
  40. */
  41. static const uint8_t expected_iter[SM4_BLOCK_SIZE] = {
  42. 0x59, 0x52, 0x98, 0xc7, 0xc6, 0xfd, 0x27, 0x1f,
  43. 0x04, 0x02, 0xf8, 0x04, 0xc3, 0x3d, 0x3f, 0x66
  44. };
  45. int i;
  46. SM4_KEY key;
  47. uint8_t block[SM4_BLOCK_SIZE];
  48. SM4_set_key(k, &key);
  49. memcpy(block, input, SM4_BLOCK_SIZE);
  50. SM4_encrypt(block, block, &key);
  51. if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, expected, SM4_BLOCK_SIZE))
  52. return 0;
  53. for (i = 0; i != 999999; ++i)
  54. SM4_encrypt(block, block, &key);
  55. if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, expected_iter, SM4_BLOCK_SIZE))
  56. return 0;
  57. for (i = 0; i != 1000000; ++i)
  58. SM4_decrypt(block, block, &key);
  59. if (!TEST_mem_eq(block, SM4_BLOCK_SIZE, input, SM4_BLOCK_SIZE))
  60. return 0;
  61. return 1;
  62. }
  63. #endif
  64. int setup_tests(void)
  65. {
  66. #ifndef OPENSSL_NO_SM4
  67. ADD_TEST(test_sm4_ecb);
  68. #endif
  69. return 1;
  70. }