Code Example For Synchronous Block Cipher Operation
static int test_blkcipher(void)
{
struct crypto_blkcipher *blkcipher = NULL;
char *cipher = "cbc(aes)";
// AES 128
charkey =
"\x12\x34\x56\x78\x90\xab\xcd\xef\x12\x34\x56\x78\x90\xab\xcd\xef";
chariv =
"\x12\x34\x56\x78\x90\xab\xcd\xef\x12\x34\x56\x78\x90\xab\xcd\xef";
unsigned int ivsize = 0;
char *scratchpad = NULL; // holds plaintext and ciphertext
struct scatterlist sg;
struct blkcipher_desc desc;
int ret = -EFAULT;
blkcipher = crypto_alloc_blkcipher(cipher, 0, 0);
if (IS_ERR(blkcipher)) {
printk("could not allocate blkcipher handle for %s\n", cipher);
return -PTR_ERR(blkcipher);
}
if (crypto_blkcipher_setkey(blkcipher, key, strlen(key))) {
printk("key could not be set\n");
ret = -EAGAIN;
goto out;
}
ivsize = crypto_blkcipher_ivsize(blkcipher);
if (ivsize) {
if (ivsize != strlen(iv))
printk("IV length differs from expected length\n");
crypto_blkcipher_set_iv(blkcipher, iv, ivsize);
}
scratchpad = kmalloc(crypto_blkcipher_blocksize(blkcipher), GFP_KERNEL);
if (!scratchpad) {
printk("could not allocate scratchpad for %s\n", cipher);
goto out;
}
/* get some random data that we want to encrypt */
get_random_bytes(scratchpad, crypto_blkcipher_blocksize(blkcipher));
desc.flags = 0;
desc.tfm = blkcipher;
sg_init_one(&sg, scratchpad, crypto_blkcipher_blocksize(blkcipher));
/* encrypt data in place */
crypto_blkcipher_encrypt(&desc, &sg, &sg,
crypto_blkcipher_blocksize(blkcipher));
/* decrypt data in place
* crypto_blkcipher_decrypt(&desc, &sg, &sg,
*/ crypto_blkcipher_blocksize(blkcipher));
printk("Cipher operation completed\n");
return 0;
out:
if (blkcipher)
crypto_free_blkcipher(blkcipher);
if (scratchpad)
kzfree(scratchpad);
return ret;
}