2 * Demo on how to use /dev/crypto device for ciphering.
4 * Placed under public domain.
12 #include <sys/ioctl.h>
13 #include <crypto/cryptodev.h>
15 #define DATA_SIZE 4096
22 char plaintext
[DATA_SIZE
];
23 char ciphertext
[DATA_SIZE
];
27 struct session_op sess
;
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
;
41 if (ioctl(cfd
, CIOCGSESSION
, &sess
)) {
42 perror("ioctl(CIOCGSESSION)");
46 /* Encrypt data.in to data.encrypted */
48 cryp
.len
= sizeof(plaintext
);
50 cryp
.dst
= ciphertext
;
52 cryp
.op
= COP_ENCRYPT
;
53 if (ioctl(cfd
, CIOCCRYPT
, &cryp
)) {
54 perror("ioctl(CIOCCRYPT)");
58 if (ioctl(cfd
, CIOCGSESSION
, &sess
)) {
59 perror("ioctl(CIOCGSESSION)");
63 /* Decrypt data.encrypted to data.decrypted */
65 cryp
.len
= sizeof(plaintext
);
66 cryp
.src
= ciphertext
;
67 cryp
.dst
= ciphertext
;
69 cryp
.op
= COP_DECRYPT
;
70 if (ioctl(cfd
, CIOCCRYPT
, &cryp
)) {
71 perror("ioctl(CIOCCRYPT)");
75 /* Verify the result */
76 if (memcmp(plaintext
, ciphertext
, sizeof(plaintext
)) != 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 */