Better name for example1.
[cryptodev-linux.git] / example-cipher.c
blob3bd261075a9556fdd42f540e4cf083e44a15936f
1 /*
2 * Demo on how to use OpenBSD /dev/crypto device.
4 * Author: Michal Ludvig <michal@logix.cz>
5 * http://www.logix.cz/michal
7 * Note: by default OpenBSD doesn't allow using
8 * /dev/crypto if there is no hardware accelerator
9 * for a given algorithm. To change this you'll have to
10 * set cryptodevallowsoft=1 in
11 * /usr/src/sys/crypto/cryptodev.c and rebuild your kernel.
13 #include <stdio.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <fcntl.h>
18 #include <sys/ioctl.h>
19 //#include <crypto/cryptodev.h>
20 #include "cryptodev.h"
22 #define DATA_SIZE 4096
23 #define BLOCK_SIZE 16
24 #define KEY_SIZE 16
26 static int
27 test_crypto(int cfd)
29 struct {
30 char in[DATA_SIZE],
31 encrypted[DATA_SIZE],
32 decrypted[DATA_SIZE],
33 iv[BLOCK_SIZE],
34 key[KEY_SIZE];
35 } data;
36 struct session_op sess;
37 struct crypt_op cryp;
39 memset(&sess, 0, sizeof(sess));
40 memset(&cryp, 0, sizeof(cryp));
42 /* Use the garbage that is on the stack :-) */
43 /* memset(&data, 0, sizeof(data)); */
45 /* Get crypto session for AES128 */
46 sess.cipher = CRYPTO_AES_CBC;
47 sess.keylen = KEY_SIZE;
48 sess.key = data.key;
49 if (ioctl(cfd, CIOCGSESSION, &sess)) {
50 perror("ioctl(CIOCGSESSION)");
51 return 1;
54 /* Encrypt data.in to data.encrypted */
55 cryp.ses = sess.ses;
56 cryp.len = sizeof(data.in);
57 cryp.src = data.in;
58 cryp.dst = data.encrypted;
59 cryp.iv = data.iv;
60 cryp.op = COP_ENCRYPT;
61 if (ioctl(cfd, CIOCCRYPT, &cryp)) {
62 perror("ioctl(CIOCCRYPT)");
63 return 1;
66 /* Decrypt data.encrypted to data.decrypted */
67 cryp.src = data.encrypted;
68 cryp.dst = data.decrypted;
69 cryp.op = COP_DECRYPT;
70 if (ioctl(cfd, CIOCCRYPT, &cryp)) {
71 perror("ioctl(CIOCCRYPT)");
72 return 1;
75 /* Verify the result */
76 if (memcmp(data.in, data.decrypted, sizeof(data.in)) != 0) {
77 fprintf(stderr,
78 "FAIL: Decrypted data are different from the input data.\n");
79 return 1;
80 } else
81 printf("Test passed\n");
83 /* Finish crypto session */
84 if (ioctl(cfd, CIOCFSESSION, &sess.ses)) {
85 perror("ioctl(CIOCFSESSION)");
86 return 1;
89 return 0;
92 int
93 main()
95 int fd = -1, cfd = -1;
97 /* Open the crypto device */
98 fd = open("/dev/crypto", O_RDWR, 0);
99 if (fd < 0) {
100 perror("open(/dev/crypto)");
101 return 1;
104 /* Clone file descriptor */
105 if (ioctl(fd, CRIOGET, &cfd)) {
106 perror("ioctl(CRIOGET)");
107 return 1;
110 /* Set close-on-exec (not really neede here) */
111 if (fcntl(cfd, F_SETFD, 1) == -1) {
112 perror("fcntl(F_SETFD)");
113 return 1;
116 /* Run the test itself */
117 if (test_crypto(cfd))
118 return 1;
120 /* Close cloned descriptor */
121 if (close(cfd)) {
122 perror("close(cfd)");
123 return 1;
126 /* Close the original descriptor */
127 if (close(fd)) {
128 perror("close(fd)");
129 return 1;
132 return 0;