1 /* 2 * Copyright 2014-2022 The GmSSL Project. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the License); you may 5 * not use this file except in compliance with the License. 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 */ 9 10 11 12 #ifndef GMSSL_AES_H 13 #define GMSSL_AES_H 14 15 #include <stdint.h> 16 #include <stdlib.h> 17 18 #ifdef __cplusplus 19 extern "C" { 20 #endif 21 22 23 #define AES128_KEY_BITS 128 24 #define AES192_KEY_BITS 192 25 #define AES256_KEY_BITS 256 26 27 #define AES128_KEY_SIZE (AES128_KEY_BITS/8) 28 #define AES192_KEY_SIZE (AES192_KEY_BITS/8) 29 #define AES256_KEY_SIZE (AES256_KEY_BITS/8) 30 31 #define AES_BLOCK_SIZE 16 32 33 #define AES128_ROUNDS 10 34 #define AES192_ROUNDS 12 35 #define AES256_ROUNDS 14 36 #define AES_MAX_ROUNDS AES256_ROUNDS 37 38 39 typedef struct { 40 uint32_t rk[4 * (AES_MAX_ROUNDS + 1)]; 41 size_t rounds; 42 } AES_KEY; 43 44 int aes_set_encrypt_key(AES_KEY *key, const uint8_t *raw_key, size_t raw_key_len); 45 int aes_set_decrypt_key(AES_KEY *key, const uint8_t *raw_key, size_t raw_key_len); 46 void aes_encrypt(const AES_KEY *key, const uint8_t in[AES_BLOCK_SIZE], uint8_t out[AES_BLOCK_SIZE]); 47 void aes_decrypt(const AES_KEY *key, const uint8_t in[AES_BLOCK_SIZE], uint8_t out[AES_BLOCK_SIZE]); 48 49 50 void aes_cbc_encrypt(const AES_KEY *key, const uint8_t iv[AES_BLOCK_SIZE], 51 const uint8_t *in, size_t nblocks, uint8_t *out); 52 void aes_cbc_decrypt(const AES_KEY *key, const uint8_t iv[AES_BLOCK_SIZE], 53 const uint8_t *in, size_t nblocks, uint8_t *out); 54 int aes_cbc_padding_encrypt(const AES_KEY *key, const uint8_t iv[AES_BLOCK_SIZE], 55 const uint8_t *in, size_t inlen, 56 uint8_t *out, size_t *outlen); 57 int aes_cbc_padding_decrypt(const AES_KEY *key, const uint8_t iv[AES_BLOCK_SIZE], 58 const uint8_t *in, size_t inlen, 59 uint8_t *out, size_t *outlen); 60 61 void aes_ctr_encrypt(const AES_KEY *key, uint8_t ctr[AES_BLOCK_SIZE], 62 const uint8_t *in, size_t inlen, uint8_t *out); 63 #define aes_ctr_decrypt(key,ctr,in,inlen,out) aes_ctr_encrypt(key,ctr,in,inlen,out) 64 65 66 #define AES_GCM_IV_MIN_SIZE 1 67 #define AES_GCM_IV_MAX_SIZE ((uint64_t)(1 << (64-3))) 68 #define AES_GCM_IV_DEFAULT_BITS 96 69 #define AES_GCM_IV_DEFAULT_SIZE 12 70 71 #define AES_GCM_MIN_AAD_SIZE 0 72 #define AES_GCM_MAX_AAD_SIZE ((uint64_t)(1 << (64-3))) 73 74 #define AES_GCM_MIN_PLAINTEXT_SIZE 0 75 #define AES_GCM_MAX_PLAINTEXT_SIZE ((((uint64_t)1 << 39) - 256) >> 3) 76 77 #define AES_GCM_MAX_TAG_SIZE 16 78 79 int aes_gcm_encrypt(const AES_KEY *key, const uint8_t *iv, size_t ivlen, 80 const uint8_t *aad, size_t aadlen, const uint8_t *in, size_t inlen, 81 uint8_t *out, size_t taglen, uint8_t *tag); 82 int aes_gcm_decrypt(const AES_KEY *key, const uint8_t *iv, size_t ivlen, 83 const uint8_t *aad, size_t aadlen, const uint8_t *in, size_t inlen, 84 const uint8_t *tag, size_t taglen, uint8_t *out); 85 86 87 #ifdef __cplusplus 88 } 89 #endif 90 #endif 91