demo_sm4_ctr_encrypt_update.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 <gmssl/sm4.h>
  13. #include <gmssl/rand.h>
  14. int main(void)
  15. {
  16. SM4_CTR_CTX cbc_ctx;
  17. unsigned char key[16] = {
  18. 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
  19. 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
  20. };
  21. unsigned char ctr[16] = {
  22. 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
  23. 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
  24. };
  25. unsigned char inbuf[1024];
  26. unsigned char outbuf[1024 + 32];
  27. size_t inlen;
  28. size_t outlen;
  29. if (sm4_ctr_encrypt_init(&cbc_ctx, key, ctr) != 1) {
  30. fprintf(stderr, "%s %d: error\n", __FILE__, __LINE__);
  31. return 1;
  32. }
  33. while ((inlen = fread(inbuf, 1, sizeof(inbuf), stdin)) > 0) {
  34. if (sm4_ctr_encrypt_update(&cbc_ctx, inbuf, inlen, outbuf, &outlen) != 1) {
  35. fprintf(stderr, "%s %d: error\n", __FILE__, __LINE__);
  36. return 1;
  37. }
  38. fwrite(outbuf, 1, outlen, stdout);
  39. }
  40. if (sm4_ctr_encrypt_finish(&cbc_ctx, outbuf, &outlen) != 1) {
  41. fprintf(stderr, "%s %d: error\n", __FILE__, __LINE__);
  42. return 1;
  43. }
  44. fwrite(outbuf, 1, outlen, stdout);
  45. return 0;
  46. }