一、由來與定位
Linux 內核從 2.5 系列開始引入了一套完整的加密框架,動機主要有三:消除各子系統各自實作的冗餘程式碼、為 IPSec 提供統一的密碼學能力,以及讓通用加密需求有標準介面可用。後續的應用方向還包括硬體加密設備驅動、內核程式碼簽章、硬體亂數產生器、檔案系統加密等等。
二、把 Crypto API 用起來
1. 編譯與安裝
自 2.6.6 起,內核源碼樹已內建豐富的密碼學演算法。只要在 menuconfig 的 Cryptographic options 區段把需要的演算法選成模組(M)編入內核,重新編譯安裝後,就能在相應目錄下看到生成的 .ko 檔。
2. 撰寫內核態程式碼
例一:計算雜湊(摘要)
char *Kern_Digest(const void *data, size_t count,
unsigned char *md, unsigned int *size,
const char *name)
{
struct crypto_tfm *tfm;
struct scatterlist sg[1];
tfm = crypto_alloc_tfm(name, 0);
sg_init_one(sg, data, count); /* 準備要做雜湊的資料 */
crypto_digest_init(tfm);
crypto_digest_update(tfm, sg, 1);
crypto_digest_final(tfm, md);
if (size != NULL)
*size = tfm->cra_digest.dia_digestsize;
crypto_free_tfm(tfm);
}
例二:對稱加密(DES)
#include <linux/crypto.h>
int len;
char key[8];
char result[64];
struct crypto_tfm *tfm;
struct scatterlist sg[2];
tfm = crypto_alloc_tfm("des", 0);
if (tfm == NULL)
fail();
crypto_cipher_setkey(tfm, key, 8);
/* 把待加密資料放進 scatterlist */
crypto_cipher_encrypt(tfm, sg[0], sg[0], len); /* 可模擬輸入輸出 */
crypto_free_tfm(tfm);
兩個例子只示範了呼叫流程,卻已點出最重要的兩組資料結構:crypto_tfm 與 scatterlist。前者是指向「演算法物件」的指標,後者則是這些演算法所操作的資料載體。
順帶一提,Crypto API 的函式命名非常自明(crypto_alloc_tfm、crypto_digest_update……),這也正是 Linux 內核命名風格的特色。所有介面都宣告在 linux/crypto.h 中,動手實作時需要具備基本的模組開發知識。