Linux 2.6.38 User-space interface for Crypto API

Linux内核里面自带非常多的加密模块,这是模块经过调优性能非常高, 而且现在又很多硬件本身支持加密功能,比如intel的CPU支持AES加密指令,那些内核的那帮人知道更好如何利用这些硬件更快的完成加密功能的, 他们写的这些硬件的驱动在drivers/crypto目录里. 所以如果我们能在用户空间的应用程序中用到这些加密库有二个好处: 1. 无须再造轮子. 2. 性能高.

幸运的是2.6.38的内核给我们带来了这些功能. 这些功能是通过socket方式暴露的,思路非常独特优雅,同时由于支持gather write, scatter read, 无须拷贝数据,性能应该非常高.

具体可以参考底下材料:
User-space interface for Crypto API : 这里这里

在ubuntu10.10下安装新的内核2.6.38, 参考这里

安装完了系统,我们可以演示下如何使用新的API调用:

$ uname -r
2.6.38-yufeng
$ cat /etc/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=10.10
DISTRIB_CODENAME=maverick
DISTRIB_DESCRIPTION="Ubuntu 10.10"
$ cat > example.c
#include <stdio.h>
#include <sys/socket.h>
#include <linux/if_alg.h>
#ifndef AF_ALG
#define AF_ALG 38
#define SOL_ALG 279
#endif
int main(void)
{
int opfd;
int tfmfd;
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
.salg_type = "hash",
.salg_name = "sha1"
};
char buf[20];
int i;
tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa));
opfd = accept(tfmfd, NULL, 0);
write(opfd, "abc", 3);
read(opfd, buf, 20);
for (i = 0; i < 20; i++) {
printf("%02x", (unsigned char)buf[i]);
}
printf("\n");
close(opfd);
close(tfmfd);
return 0;
}
CTRL+D
$ mkdir -p linux && cp /usr/src/linux-2.6.38/include/linux/if_alg.h linux/
$ gcc -I linux example.c
$ ./a.out
687b37ba3c7f0000100940000000000000000000

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.