Corrected example
[cryptodev-linux.git] / example-cipher.c
blob500d773aebbf0ad695fdfd13c53d0b8582e279da
1 /*
2 * Demo on how to use /dev/crypto device for ciphering.
4 * Placed under public domain.
6 */
7 #include <stdio.h>
8 #include <string.h>
9 #include <unistd.h>
10 #include <fcntl.h>
12 #include <sys/ioctl.h>
13 #include <crypto/cryptodev.h>
15 #define DATA_SIZE 4096
16 #define BLOCK_SIZE 16
17 #define KEY_SIZE 16
19 static int
20 test_crypto(int cfd)
22 char plaintext[DATA_SIZE];
23 char ciphertext[DATA_SIZE];
24 char iv[BLOCK_SIZE];
25 char key[KEY_SIZE];
27 struct session_op sess;
28 struct crypt_op cryp;
30 memset(&sess, 0, sizeof(sess));
31 memset(&cryp, 0, sizeof(cryp));
33 memset(&plaintext, 0x15, sizeof(plaintext));
34 memset(&key, 0x33, sizeof(key));
35 memset(&iv, 0x03, sizeof(iv));
37 /* Get crypto session for AES128 */
38 sess.cipher = CRYPTO_AES_CBC;
39 sess.keylen = KEY_SIZE;
40 sess.key = key;
41 if (ioctl(cfd, CIOCGSESSION, &sess)) {
42 perror("ioctl(CIOCGSESSION)");
43 return 1;
46 /* Encrypt data.in to data.encrypted */
47 cryp.ses = sess.ses;
48 cryp.len = sizeof(plaintext);
49 cryp.src = plaintext;
50 cryp.dst = ciphertext;
51 cryp.iv = iv;
52 cryp.op = COP_ENCRYPT;
53 if (ioctl(cfd, CIOCCRYPT, &cryp)) {
54 perror("ioctl(CIOCCRYPT)");
55 return 1;
58 if (ioctl(cfd, CIOCGSESSION, &sess)) {
59 perror("ioctl(CIOCGSESSION)");
60 return 1;
63 /* Decrypt data.encrypted to data.decrypted */
64 cryp.ses = sess.ses;
65 cryp.len = sizeof(plaintext);
66 cryp.src = ciphertext;
67 cryp.dst = ciphertext;
68 cryp.iv = iv;
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(plaintext, ciphertext, sizeof(plaintext)) != 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;