那么ctx被分配到哪里了呢?这个跟另外一个数据结构有关,就是接下来要讲的struct crypto_tfm。我们先来看crypto_alg对应的set_key、encrypt、decrypt这三个函数的函数原型(注意这里的表述哦,是crypto_alg对应的三大函数)。
int set_key(struct crypto_tfm *tfm, const u8 *in_key, unsigned int key_len);
void encrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in);
void decrypt(struct crypto_tfm *tfm, u8 *out, const u8 *in);
in和out参数就是加解密之前和之后的传入传出数据,长度就是alg中的blocksize。这三个函数都有类型为struct crypto_tfm *的参数。tfm是transform的缩写。所有加密、哈希算法的set_key、encrypt、decrypt都带有这个参数。crypto_tfm的定义在<srcdir>/include/linux/crypto.h中:
- #define crt_ablkcipher crt_u.ablkcipher
- #define crt_aead crt_u.aead
- #define crt_blkcipher crt_u.blkcipher
- #define crt_cipher crt_u.cipher
- #define crt_hash crt_u.hash
- #define crt_compress crt_u.compress
- #define crt_rng crt_u.rng
- struct crypto_tfm {
- u32 crt_flags;
- union {
- struct ablkcipher_tfm ablkcipher;
- struct aead_tfm aead;
- struct blkcipher_tfm blkcipher;
- struct cipher_tfm cipher;
- struct hash_tfm hash;
- struct compress_tfm compress;
- struct rng_tfm rng;
- } crt_u;
- void (*exit)(struct crypto_tfm *tfm);
- struct crypto_alg *__crt_alg;
- void *__crt_ctx[] CRYPTO_MINALIGN_ATTR;
- };
从中间那个union和上面的一堆#define可以看出,从这个结构又可以分散出一组xxx_tfm。crypto_alg对应cipher_tfm。最后那个参数__crt_ctx[]就是上面说到的算法上下文。也就是说,算法上下文是跟随tfm一起分配的。从tfm,我们就可以得到ctx。Linux提供了一个函数inline void *crypto_tfm_ctx(struct crypto_tfm *tfm);来进行转换,该函数也在<srcdir>/include/linux/crypto.h中。
现在可以梳理一下alg、crypto_tfm、xxx_tfm、ctx的关系了。alg是注册用的;crypto_tfm是每个算法实例对应的结构;xxx_tfm包含在crypto_tfm中,是每类算法对应的结构,ctx在crypto_tfm的最后。当你的算法拿到一个crypto_tfm指针时,可以通过__crt_alg指针访问到alg结构、可以通过crt_u.xxx访问到对应算法类别的xxx_tfm结构、可以通过__crt_ctx得到ctx指针。当你的算法拿到一个xxx_tfm结构体指针时,可以利用xxx_tfm内嵌在crypto_tfm中的这层关系,使用container_of操作反向获得crypto_tfm指针,由此获得其他的结构指针。当然,你无需直接访问成员,而是使用<srcdir>/include/crypto/algapi.h中定义的那一堆内联函数来实现。但是你要看懂并正确使用那些函数之前,还是先弄懂上述关系,否则就会跟我初看这堆代码一样——脑细胞都拧成麻花了。
现在,一个普通的分组加密算法就很好理解了。首先声明一个crypto_alg结构注册到密码管理器中,当外界使用到该算法时,密码管理器会自动创建crypto_tfm并调用那三大函数进行加解密操作,对应函数返回就表示操作已完成,属于同步操作。接下来要讲的块加密其实也是类似的。
