cipher_sm4_gcm_hw.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright 2021-2022 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. * Generic support for SM4 GCM.
  11. */
  12. #include "cipher_sm4_gcm.h"
  13. #include "crypto/sm4_platform.h"
  14. static int sm4_gcm_initkey(PROV_GCM_CTX *ctx, const unsigned char *key,
  15. size_t keylen)
  16. {
  17. PROV_SM4_GCM_CTX *actx = (PROV_SM4_GCM_CTX *)ctx;
  18. SM4_KEY *ks = &actx->ks.ks;
  19. ctx->ks = ks;
  20. # ifdef HWSM4_CAPABLE
  21. if (HWSM4_CAPABLE) {
  22. HWSM4_set_encrypt_key(key, ks);
  23. CRYPTO_gcm128_init(&ctx->gcm, ks, (block128_f) HWSM4_encrypt);
  24. # ifdef HWSM4_ctr32_encrypt_blocks
  25. ctx->ctr = (ctr128_f) HWSM4_ctr32_encrypt_blocks;
  26. # else /* HWSM4_ctr32_encrypt_blocks */
  27. ctx->ctr = (ctr128_f)NULL;
  28. # endif
  29. } else
  30. # endif /* HWSM4_CAPABLE */
  31. # ifdef VPSM4_CAPABLE
  32. if (VPSM4_CAPABLE) {
  33. vpsm4_set_encrypt_key(key, ks);
  34. CRYPTO_gcm128_init(&ctx->gcm, ks, (block128_f) vpsm4_encrypt);
  35. ctx->ctr = (ctr128_f) vpsm4_ctr32_encrypt_blocks;
  36. } else
  37. # endif /* VPSM4_CAPABLE */
  38. {
  39. ossl_sm4_set_key(key, ks);
  40. CRYPTO_gcm128_init(&ctx->gcm, ks, (block128_f)ossl_sm4_encrypt);
  41. ctx->ctr = (ctr128_f)NULL;
  42. }
  43. ctx->key_set = 1;
  44. return 1;
  45. }
  46. static int hw_gcm_cipher_update(PROV_GCM_CTX *ctx, const unsigned char *in,
  47. size_t len, unsigned char *out)
  48. {
  49. if (ctx->enc) {
  50. if (ctx->ctr != NULL) {
  51. if (CRYPTO_gcm128_encrypt_ctr32(&ctx->gcm, in, out, len, ctx->ctr))
  52. return 0;
  53. } else {
  54. if (CRYPTO_gcm128_encrypt(&ctx->gcm, in, out, len))
  55. return 0;
  56. }
  57. } else {
  58. if (ctx->ctr != NULL) {
  59. if (CRYPTO_gcm128_decrypt_ctr32(&ctx->gcm, in, out, len, ctx->ctr))
  60. return 0;
  61. } else {
  62. if (CRYPTO_gcm128_decrypt(&ctx->gcm, in, out, len))
  63. return 0;
  64. }
  65. }
  66. return 1;
  67. }
  68. static const PROV_GCM_HW sm4_gcm = {
  69. sm4_gcm_initkey,
  70. ossl_gcm_setiv,
  71. ossl_gcm_aad_update,
  72. hw_gcm_cipher_update,
  73. ossl_gcm_cipher_final,
  74. ossl_gcm_one_shot
  75. };
  76. const PROV_GCM_HW *ossl_prov_sm4_hw_gcm(size_t keybits)
  77. {
  78. return &sm4_gcm;
  79. }