openssl编程--AES_ctr128_encrypt()

计算器模式(Counter (CTR))
计算器模式不常见,在CTR模式中, 有一个自增的算子,这个算子用密钥加密之后的输出和明文异或的结果得到密文,相当于一次一密。这种加密方式简单快速,安全可靠,而且可以并行加密,但是 在计算器不能维持很长的情况下,密钥只能使用一次 。

#include <openssl/aes.h>
#include <openssl/rand.h> 
#include <openssl/hmac.h>
#include <openssl/buffer.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

// Code example uses partail code from: http://stackoverflow.com/questions/3141860/aes-ctr-256-encryption-mode-of-operation-on-openssl
// Mostly in the ctr_ state, and init_ctr functions. 

struct ctr_state 
{ 
    unsigned char ivec[AES_BLOCK_SIZE];  
    unsigned int num; 
    unsigned char ecount[AES_BLOCK_SIZE]; 
}; 
AES_KEY key; 

int bytes_read, bytes_written;   
unsigned char indata[AES_BLOCK_SIZE]; 
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE]; //16?
struct ctr_state state;


int init_ctr(struct ctr_state *state, const unsigned char iv[16])
{        
    /*O aes_ctr128_encrypt exige um 'num' e um 'ecount' definidos a zero na primeira chamada. */
    state->num = 0;
    memset(state->ecount, 0, AES_BLOCK_SIZE); //16?

    /* Inicilaização do contador no 'ivec' a 0 */
    memset(state->ecount, 0, 16); //16?

    /* Copia o IV para o 'ivec' */
    memcpy(state->ivec, iv, 16); //16?
}

char * TextEncrypt(const unsigned char* enc_key, char * text,int bytes_read)
{ 
    //Cria vector com valores aleatórios
    if(!RAND_bytes(iv, AES_BLOCK_SIZE))
    {
        printf("Erro: Não foi possivel criar bytes aleatorios.\n");
        exit(1);    
    }

    //Inicializa a chave de encriptação
    if (AES_set_encrypt_key(enc_key, 128, &key) < 0)
    {
        fprintf(stderr, "Nao foi possível definir chave de encriptacao.");
        exit(1);
    }

    init_ctr(&state, iv); //Chamada do contador

  //  bytes_read = strlen(text);

    AES_set_encrypt_key(enc_key, 128, &key);    

    //Encripta em blocos de 16 bytes e guarda o texto cifrado numa string -> outdata
    AES_ctr128_encrypt(text, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);

    fflush(stdin);
    return outdata;
}

char * TextDecrypt(const unsigned char* enc_key, unsigned char* cypherText,int bytes_read)
{       

    //Inicialização da Chave de encriptação 
    if (AES_set_encrypt_key(enc_key, 128, &key) < 0)
    {
        fprintf(stderr, "Nao foi possível definir chave de decodificacao.");
        exit(1);
    }

    init_ctr(&state, iv);//Chamada do contador

    //Encripta em blocos de 16 bytes e escreve o ficheiro output.txt cifrado         
   // bytes_read = strlen(cypherText);    

    AES_set_encrypt_key(enc_key, 128, &key);

    AES_ctr128_encrypt(cypherText, outdata, bytes_read, &key, state.ivec, state.ecount, &state.num);

    fflush(stdin);
    return outdata;
}

int main(int argc, char *argv[])
{
    char text [] = "Text test to my program";

    //Receive hexadecimal 128 bits key 
    unsigned const char * key = "1234567812345678";
    //unsigned const char * key = "9EF4BCDE";   
    char * cipher, * decrypted;

    printf("Clean text: %s\n", text);
    int len = strlen(text);

    cipher = TextEncrypt(key, text,len);
    printf("Chiper text: %s\n", cipher);


    decrypted = TextDecrypt(key, cipher,len);
    printf("Decrypted text: %s\n", decrypted);

    getc(stdin);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`AES_ctr128_encrypt()` 函数是 OpenSSL 库中的一个函数,用于执行 AES-CTR 加密。它的作用是将明文数据按指定的密钥和计数器进行加密,生成密文数据。 该函数封装了以下步骤: 1. 通过 `AES_set_encrypt_key()` 函数设置 AES 加密密钥。 2. 通过 `CTR_MODE` 模式初始化一个 AES 加密上下文。 3. 使用 `AES_ctr128_encrypt()` 函数对明文数据进行加密,生成密文数据。 以下是使用 `AES_ctr128_encrypt()` 函数进行加密和解密的示例代码: ```c #include <openssl/aes.h> void encrypt_decrypt_data(unsigned char *data, int data_len, unsigned char *key, unsigned char *iv) { AES_KEY aes_key; AES_set_encrypt_key(key, 128, &aes_key); AES_ctr128_encrypt(data, data, data_len, &aes_key, iv, AES_ENCRYPT); } int main() { unsigned char key[16] = {0x00, 0x01, 0x02, ..., 0x0F}; unsigned char iv[16] = {0x00, 0x00, 0x00, ..., 0x00}; unsigned char plaintext[1024] = "Hello, world!"; int plaintext_len = strlen(plaintext); encrypt_decrypt_data(plaintext, plaintext_len, key, iv); printf("Encrypted data: %s\n", plaintext); // Decrypt the data AES_KEY aes_key; AES_set_encrypt_key(key, 128, &aes_key); AES_ctr128_encrypt(plaintext, plaintext, plaintext_len, &aes_key, iv, AES_DECRYPT); printf("Decrypted data: %s\n", plaintext); return 0; } ``` 在上面的示例代码中,我们首先定义了一个 AES 加密密钥和一个计数器。然后定义了一个需要加密的明文数据,并计算出它的长度。接着,我们调用 `encrypt_decrypt_data()` 函数对明文数据进行加密,并输出加密后的密文数据。最后,我们将密文数据传递给 `AES_ctr128_encrypt()` 函数进行解密,并输出解密后的明文数据。 注意,使用 AES-CTR 模式进行加密时,计数器需要在每次加密时自增。因此,我们需要在加密和解密时使用相同的计数器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值