/* * Demo on how to use /dev/crypto device for ciphering. * * Placed under public domain. * */ #include #include #include #include #include #include #include #define DATA_SIZE (8*1024) #define HEADER_SIZE 193 #define PLAINTEXT_SIZE 1021 #define FOOTER_SIZE 15 #define BLOCK_SIZE 16 #define KEY_SIZE 16 #define MAC_SIZE 20 /* SHA1 */ static int debug = 0; static int get_sha1_hmac(int cfd, void* key, int key_size, void* data, int data_size, void* mac) { struct session_op sess; struct crypt_op cryp; memset(&sess, 0, sizeof(sess)); memset(&cryp, 0, sizeof(cryp)); sess.cipher = 0; sess.mac = CRYPTO_SHA1_HMAC; sess.mackeylen = key_size; sess.mackey = key; if (ioctl(cfd, CIOCGSESSION, &sess)) { perror("ioctl(CIOCGSESSION)"); return 1; } /* Encrypt data.in to data.encrypted */ cryp.ses = sess.ses; cryp.len = data_size; cryp.src = data; cryp.dst = NULL; cryp.iv = NULL; cryp.mac = mac; cryp.op = COP_ENCRYPT; if (ioctl(cfd, CIOCCRYPT, &cryp)) { perror("ioctl(CIOCCRYPT)"); return 1; } /* Finish crypto session */ if (ioctl(cfd, CIOCFSESSION, &sess.ses)) { perror("ioctl(CIOCFSESSION)"); return 1; } return 0; } static void print_buf(char* desc, unsigned char* buf, int size) { int i; fputs(desc, stderr); for (i=0;i 1) debug = 1; /* Open the crypto device */ fd = open("/dev/crypto", O_RDWR, 0); if (fd < 0) { perror("open(/dev/crypto)"); return 1; } /* Clone file descriptor */ if (ioctl(fd, CRIOGET, &cfd)) { perror("ioctl(CRIOGET)"); return 1; } /* Set close-on-exec (not really neede here) */ if (fcntl(cfd, F_SETFD, 1) == -1) { perror("fcntl(F_SETFD)"); return 1; } /* Run the test itself */ if (test_crypto(cfd)) return 1; if (test_encrypt_decrypt(cfd)) return 1; if (test_encrypt_decrypt_error(cfd,0)) return 1; if (test_encrypt_decrypt_error(cfd,1)) return 1; /* Close cloned descriptor */ if (close(cfd)) { perror("close(cfd)"); return 1; } /* Close the original descriptor */ if (close(fd)) { perror("close(fd)"); return 1; } return 0; }