首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AES CTR对称加解密

AES CTR对称加解密
EN

Stack Overflow用户
提问于 2014-12-16 00:00:00
回答 1查看 1.8K关注 0票数 1

我不是openssl方面的专家。我把下面的代码放在一起,用AES-CTR加密和解密一条消息.输出结果不是我所期望看到的。

代码语言:javascript
复制
#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&nu9♫_╠╠╠╠╠╠╠╠”▬♂☻e0T§▓→♀诉╠╠╠╠╠╠╠╠嘿“

知道是什么原因造成的吗?我所要做的就是使用AES使用CTR加密和解密消息。我希望获得与明文(或+1字节)相同的加密长度。我用DES做过,但DES不安全。然后,我将使用AES-CTR加密和解密我的网络流量(流)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-16 02:14:02

您需要在解密前重置:

代码语言:javascript
复制
…
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);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27495370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档