Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 
0003 /*
0004  * SM4 Cipher Algorithm.
0005  *
0006  * Copyright (C) 2018 ARM Limited or its affiliates.
0007  * All rights reserved.
0008  */
0009 
0010 #include <crypto/sm4.h>
0011 #include <linux/module.h>
0012 #include <linux/init.h>
0013 #include <linux/types.h>
0014 #include <linux/errno.h>
0015 #include <linux/crypto.h>
0016 #include <asm/byteorder.h>
0017 #include <asm/unaligned.h>
0018 
0019 /**
0020  * sm4_setkey - Set the SM4 key.
0021  * @tfm:    The %crypto_tfm that is used in the context.
0022  * @in_key: The input key.
0023  * @key_len:    The size of the key.
0024  *
0025  * This function uses sm4_expandkey() to expand the key.
0026  * &sm4_ctx _must_ be the private data embedded in @tfm which is
0027  * retrieved with crypto_tfm_ctx().
0028  *
0029  * Return: 0 on success; -EINVAL on failure (only happens for bad key lengths)
0030  */
0031 static int sm4_setkey(struct crypto_tfm *tfm, const u8 *in_key,
0032                unsigned int key_len)
0033 {
0034     struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
0035 
0036     return sm4_expandkey(ctx, in_key, key_len);
0037 }
0038 
0039 /* encrypt a block of text */
0040 
0041 static void sm4_encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
0042 {
0043     const struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
0044 
0045     sm4_crypt_block(ctx->rkey_enc, out, in);
0046 }
0047 
0048 /* decrypt a block of text */
0049 
0050 static void sm4_decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in)
0051 {
0052     const struct sm4_ctx *ctx = crypto_tfm_ctx(tfm);
0053 
0054     sm4_crypt_block(ctx->rkey_dec, out, in);
0055 }
0056 
0057 static struct crypto_alg sm4_alg = {
0058     .cra_name       =   "sm4",
0059     .cra_driver_name    =   "sm4-generic",
0060     .cra_priority       =   100,
0061     .cra_flags      =   CRYPTO_ALG_TYPE_CIPHER,
0062     .cra_blocksize      =   SM4_BLOCK_SIZE,
0063     .cra_ctxsize        =   sizeof(struct sm4_ctx),
0064     .cra_module     =   THIS_MODULE,
0065     .cra_u          =   {
0066         .cipher = {
0067             .cia_min_keysize    =   SM4_KEY_SIZE,
0068             .cia_max_keysize    =   SM4_KEY_SIZE,
0069             .cia_setkey     =   sm4_setkey,
0070             .cia_encrypt        =   sm4_encrypt,
0071             .cia_decrypt        =   sm4_decrypt
0072         }
0073     }
0074 };
0075 
0076 static int __init sm4_init(void)
0077 {
0078     return crypto_register_alg(&sm4_alg);
0079 }
0080 
0081 static void __exit sm4_fini(void)
0082 {
0083     crypto_unregister_alg(&sm4_alg);
0084 }
0085 
0086 subsys_initcall(sm4_init);
0087 module_exit(sm4_fini);
0088 
0089 MODULE_DESCRIPTION("SM4 Cipher Algorithm");
0090 MODULE_LICENSE("GPL v2");
0091 MODULE_ALIAS_CRYPTO("sm4");
0092 MODULE_ALIAS_CRYPTO("sm4-generic");