2 * Demo on how to use /dev/crypto device for ciphering.
4 * Placed under public domain.
11 #include <sys/ioctl.h>
12 #include <crypto/cryptodev.h>
15 int sha_ctx_init(struct cryptodev_ctx
* ctx
, int cfd
, const uint8_t *key
, unsigned int key_size
)
18 struct session_info_op siop
;
21 memset(ctx
, 0, sizeof(*ctx
));
25 ctx
->sess
.mac
= CRYPTO_SHA1
;
27 ctx
->sess
.mac
= CRYPTO_SHA1_HMAC
;
28 ctx
->sess
.mackeylen
= key_size
;
29 ctx
->sess
.mackey
= (void*)key
;
31 if (ioctl(ctx
->cfd
, CIOCGSESSION
, &ctx
->sess
)) {
32 perror("ioctl(CIOCGSESSION)");
37 siop
.ses
= ctx
->sess
.ses
;
38 if (ioctl(ctx
->cfd
, CIOCGSESSINFO
, &siop
)) {
39 perror("ioctl(CIOCGSESSINFO)");
42 printf("Got %s with driver %s\n",
43 siop
.hash_info
.cra_name
, siop
.hash_info
.cra_driver_name
);
44 if (!(siop
.flags
& SIOP_FLAG_KERNEL_DRIVER_ONLY
)) {
45 printf("Note: This is not an accelerated cipher\n");
47 /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask);*/
48 ctx
->alignmask
= siop
.alignmask
;
53 void sha_ctx_deinit(struct cryptodev_ctx
* ctx
)
55 if (ioctl(ctx
->cfd
, CIOCFSESSION
, &ctx
->sess
.ses
)) {
56 perror("ioctl(CIOCFSESSION)");
61 sha_hash(struct cryptodev_ctx
* ctx
, const void* text
, size_t size
, void* digest
)
66 /* check text and ciphertext alignment */
68 p
= (void*)(((unsigned long)text
+ ctx
->alignmask
) & ~ctx
->alignmask
);
70 fprintf(stderr
, "text is not aligned\n");
75 memset(&cryp
, 0, sizeof(cryp
));
77 /* Encrypt data.in to data.encrypted */
78 cryp
.ses
= ctx
->sess
.ses
;
80 cryp
.src
= (void*)text
;
82 if (ioctl(ctx
->cfd
, CIOCCRYPT
, &cryp
)) {
83 perror("ioctl(CIOCCRYPT)");
94 struct cryptodev_ctx ctx
;
96 char text
[] = "The quick brown fox jumps over the lazy dog";
97 uint8_t expected
[] = "\x2f\xd4\xe1\xc6\x7a\x2d\x28\xfc\xed\x84\x9e\xe1\xbb\x76\xe7\x39\x1b\x93\xeb\x12";
99 /* Open the crypto device */
100 cfd
= open("/dev/crypto", O_RDWR
, 0);
102 perror("open(/dev/crypto)");
106 /* Set close-on-exec (not really neede here) */
107 if (fcntl(cfd
, F_SETFD
, 1) == -1) {
108 perror("fcntl(F_SETFD)");
112 sha_ctx_init(&ctx
, cfd
, NULL
, 0);
114 sha_hash(&ctx
, text
, strlen(text
), digest
);
116 sha_ctx_deinit(&ctx
);
119 for (i
= 0; i
< 20; i
++) {
120 printf("%02x:", digest
[i
]);
124 if (memcmp(digest
, expected
, 20) != 0) {
125 fprintf(stderr
, "SHA1 hashing failed\n");
129 /* Close the original descriptor */
131 perror("close(cfd)");