sm4_generic.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * SM4 Cipher Algorithm.
  4. *
  5. * Copyright (C) 2018 ARM Limited or its affiliates.
  6. * All rights reserved.
  7. */
  8. #include <crypto/sm4.h>
  9. #include <linux/module.h>
  10. #include <linux/init.h>
  11. #include <linux/types.h>
  12. #include <linux/errno.h>
  13. #include <linux/crypto.h>
  14. #include <asm/byteorder.h>
  15. #include <asm/unaligned.h>
  16. /**
  17. * sm4_setkey - Set the SM4 key.
  18. * @tfm: The %crypto_tfm that is used in the context.
  19. * @in_key: The input key.
  20. * @key_len: The size of the key.
  21. *
  22. * This function uses sm4_expandkey() to expand the key.
  23. * &sm4_ctx _must_ be the private data embedded in @tfm which is
  24. * retrieved with crypto_tfm_ctx().
  25. *
  26. * Return: 0 on success; -EINVAL on failure (only happens for bad key lengths)
  27. */
  28. static int sm4_setkey(struct crypto_tfm *tfm, const u8 *in_key,
  29. unsigned int key_len)
  30. {
  31. struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
  32. return sm4_expandkey(ctx, in_key, key_len);
  33. }
  34. /* encrypt a block of text */
  35. static void sm4_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
  36. {
  37. const struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
  38. sm4_crypt_block(ctx->rkey_enc, out, in);
  39. }
  40. /* decrypt a block of text */
  41. static void sm4_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
  42. {
  43. const struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
  44. sm4_crypt_block(ctx->rkey_dec, out, in);
  45. }
  46. static struct crypto_alg sm4_alg = {
  47. .cra_name = "sm4",
  48. .cra_driver_name = "sm4-generic",
  49. .cra_priority = 100,
  50. .cra_flags = CRYPTO_ALG_TYPE_CIPHER,
  51. .cra_blocksize = SM4_BLOCK_SIZE,
  52. .cra_ctxsize = sizeof(struct sm4_ctx),
  53. .cra_module = THIS_MODULE,
  54. .cra_u = {
  55. .cipher = {
  56. .cia_min_keysize = SM4_KEY_SIZE,
  57. .cia_max_keysize = SM4_KEY_SIZE,
  58. .cia_setkey = sm4_setkey,
  59. .cia_encrypt = sm4_encrypt,
  60. .cia_decrypt = sm4_decrypt
  61. }
  62. }
  63. };
  64. static int __init sm4_init(void)
  65. {
  66. return crypto_register_alg(&sm4_alg);
  67. }
  68. static void __exit sm4_fini(void)
  69. {
  70. crypto_unregister_alg(&sm4_alg);
  71. }
  72. subsys_initcall(sm4_init);
  73. module_exit(sm4_fini);
  74. MODULE_DESCRIPTION("SM4 Cipher Algorithm");
  75. MODULE_LICENSE("GPL v2");
  76. MODULE_ALIAS_CRYPTO("sm4");
  77. MODULE_ALIAS_CRYPTO("sm4-generic");