AES CTR对称加密和解密

时间:2014-12-16 00:00:01

标签: c openssl aes encryption-symmetric

我不是openssl的专家。我已经将以下代码放在一起使用AES-CTR加密和解密邮件。输出不是我期望看到的。

#include "stdafx.h"
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <tchar.h>
#include <psapi.h>
#include <openssl/rand.h> //for RAND_bytes function

struct ctr_state {
    unsigned char ivec[16];  /* ivec[0..7] is the IV, ivec[8..15] is the big-endian counter */
    unsigned int num;
    unsigned char ecount[16];
};

int init_ctr(struct ctr_state *state, const unsigned char iv[8])
{
    /* aes_ctr128_encrypt requires 'num' and 'ecount' set to zero on the
    * first call. */
    state->num = 0;
    memset(state->ecount, 0, 16);
    /* Initialise counter in 'ivec' to 0 */
    memset(state->ivec + 8, 0, 8);
    /* Copy IV into 'ivec' */
    memcpy(state->ivec, iv, 8);
    return(0);
}

int main(int argc, char **argv)
{
    unsigned char key[] = "thiskeyisverybad"; // It is 128bits though..
    unsigned char iv[8];
    struct ctr_state state;
    if (!RAND_bytes(iv, 8))
         printf("\nError in RAND_Bytes...\n");
    init_ctr(&state, iv);
    AES_KEY aes_key;
    AES_set_encrypt_key(key, 128, &aes_key);
    char msg[] = "hey";
    unsigned char cipher[AES_BLOCK_SIZE];
    char plain[AES_BLOCK_SIZE];
    AES_ctr128_encrypt((unsigned char *) msg, cipher, AES_BLOCK_SIZE, &aes_key, state.ivec, state.ecount, &state.num);
    AES_ctr128_encrypt(cipher, (unsigned char *) plain, AES_BLOCK_SIZE, &aes_key, state.ivec, state.ecount, &state.num);
    printf("\nPLAIN:%s\n", plain);
    return 0;
}

我得到的结果是这样的:“PLAIN:¢u∩U└■My&amp; nu9♫_╠╠╠╠╠╠╠╠”Åä▬♂☻e0Tç§▓→♀v╠╠╠ ╠╠╠╠╠hey“

知道是什么原因引起的吗?我想要做的就是使用点击率来加密和解密消息。我想获得与明文(或+1字节)相同的加密长度。我用DES做了这个,但DES并不安全。然后,我将使用AES-CTR加密和解密我的网络流量(流)。

1 个答案:

答案 0 :(得分:3)

您需要在解密之前重置:

…
init_ctr(&state, iv);
AES_ctr128_encrypt(
        cipher,
        (unsigned char *) plain,
        AES_BLOCK_SIZE,
        &aes_key,
        state.ivec,
        state.ecount,
        &state.num
        );
printf("\nPLAIN:%s\n", plain);
相关问题