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.
18 #include <sys/ioctl.h>
19 //#include <crypto/cryptodev.h>
20 #include "cryptodev.h"
22 #define DATA_SIZE 4096
36 struct session_op sess
;
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
;
49 if (ioctl(cfd
, CIOCGSESSION
, &sess
)) {
50 perror("ioctl(CIOCGSESSION)");
54 /* Encrypt data.in to data.encrypted */
56 cryp
.len
= sizeof(data
.in
);
58 cryp
.dst
= data
.encrypted
;
60 cryp
.op
= COP_ENCRYPT
;
61 if (ioctl(cfd
, CIOCCRYPT
, &cryp
)) {
62 perror("ioctl(CIOCCRYPT)");
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)");
75 /* Verify the result */
76 if (memcmp(data
.in
, data
.decrypted
, sizeof(data
.in
)) != 0) {
78 "FAIL: Decrypted data are different from the input data.\n");
81 printf("Test passed\n");
83 /* Finish crypto session */
84 if (ioctl(cfd
, CIOCFSESSION
, &sess
.ses
)) {
85 perror("ioctl(CIOCFSESSION)");
95 int fd
= -1, cfd
= -1;
97 /* Open the crypto device */
98 fd
= open("/dev/crypto", O_RDWR
, 0);
100 perror("open(/dev/crypto)");
104 /* Clone file descriptor */
105 if (ioctl(fd
, CRIOGET
, &cfd
)) {
106 perror("ioctl(CRIOGET)");
110 /* Set close-on-exec (not really neede here) */
111 if (fcntl(cfd
, F_SETFD
, 1) == -1) {
112 perror("fcntl(F_SETFD)");
116 /* Run the test itself */
117 if (test_crypto(cfd
))
120 /* Close cloned descriptor */
122 perror("close(cfd)");
126 /* Close the original descriptor */