2 * Demo on how to use /dev/crypto device for ciphering.
4 * Placed under public domain.
11 #include <sys/ioctl.h>
12 #include <crypto/cryptodev.h>
15 /* This is the TLS version of AES-CBC with HMAC-SHA1.
18 int aes_sha1_ctx_init(struct cryptodev_ctx
* ctx
, int cfd
,
19 const uint8_t *key
, unsigned int key_size
,
20 const uint8_t *mac_key
, unsigned int mac_key_size
)
23 struct session_info_op siop
;
26 memset(ctx
, 0, sizeof(*ctx
));
29 ctx
->sess
.cipher
= CRYPTO_AES_CBC
;
30 ctx
->sess
.keylen
= key_size
;
31 ctx
->sess
.key
= (void*)key
;
33 ctx
->sess
.mac
= CRYPTO_SHA1_HMAC
;
34 ctx
->sess
.mackeylen
= mac_key_size
;
35 ctx
->sess
.mackey
= (void*)mac_key
;
37 if (ioctl(ctx
->cfd
, CIOCGSESSION
, &ctx
->sess
)) {
38 perror("ioctl(CIOCGSESSION)");
43 siop
.ses
= ctx
->sess
.ses
;
44 if (ioctl(ctx
->cfd
, CIOCGSESSINFO
, &siop
)) {
45 perror("ioctl(CIOCGSESSINFO)");
48 printf("Got %s with driver %s\n",
49 siop
.cipher_info
.cra_name
, siop
.cipher_info
.cra_driver_name
);
50 if (!(siop
.flags
& SIOP_FLAG_KERNEL_DRIVER_ONLY
)) {
51 printf("Note: This is not an accelerated cipher\n");
53 /*printf("Alignmask is %x\n", (unsigned int)siop.alignmask); */
54 ctx
->alignmask
= siop
.alignmask
;
59 void aes_sha1_ctx_deinit(struct cryptodev_ctx
* ctx
)
61 if (ioctl(ctx
->cfd
, CIOCFSESSION
, &ctx
->sess
.ses
)) {
62 perror("ioctl(CIOCFSESSION)");
67 aes_sha1_encrypt(struct cryptodev_ctx
* ctx
, const void* iv
,
68 const void* auth
, size_t auth_size
,
69 void* plaintext
, size_t size
)
71 struct crypt_auth_op cryp
;
74 /* check plaintext and ciphertext alignment */
76 p
= (void*)(((unsigned long)plaintext
+ ctx
->alignmask
) & ~ctx
->alignmask
);
78 fprintf(stderr
, "plaintext is not aligned\n");
83 memset(&cryp
, 0, sizeof(cryp
));
85 /* Encrypt data.in to data.encrypted */
86 cryp
.ses
= ctx
->sess
.ses
;
88 cryp
.op
= COP_ENCRYPT
;
89 cryp
.auth_len
= auth_size
;
90 cryp
.auth_src
= (void*)auth
;
92 cryp
.src
= (void*)plaintext
;
94 cryp
.flags
= COP_FLAG_AEAD_TLS_TYPE
;
95 if (ioctl(ctx
->cfd
, CIOCAUTHCRYPT
, &cryp
)) {
96 perror("ioctl(CIOCAUTHCRYPT)");
104 aes_sha1_decrypt(struct cryptodev_ctx
* ctx
, const void* iv
,
105 const void* auth
, size_t auth_size
,
106 void* ciphertext
, size_t size
)
108 struct crypt_auth_op cryp
;
111 /* check plaintext and ciphertext alignment */
112 if (ctx
->alignmask
) {
113 p
= (void*)(((unsigned long)ciphertext
+ ctx
->alignmask
) & ~ctx
->alignmask
);
114 if (ciphertext
!= p
) {
115 fprintf(stderr
, "ciphertext is not aligned\n");
120 memset(&cryp
, 0, sizeof(cryp
));
122 /* Encrypt data.in to data.encrypted */
123 cryp
.ses
= ctx
->sess
.ses
;
125 cryp
.op
= COP_DECRYPT
;
126 cryp
.auth_len
= auth_size
;
127 cryp
.auth_src
= (void*)auth
;
129 cryp
.src
= (void*)ciphertext
;
130 cryp
.dst
= ciphertext
;
131 cryp
.flags
= COP_FLAG_AEAD_TLS_TYPE
;
132 if (ioctl(ctx
->cfd
, CIOCAUTHCRYPT
, &cryp
)) {
133 perror("ioctl(CIOCAUTHCRYPT)");