AES128-ecb加解密

问题

最近使用AES加解密的过程中遇到了一些问题,我这段采用的是openssl的AES.h的库进行加密的,因为传输的数据并不重要,考虑到并发性和安全性的原因,采用了AES128-ecb的加密模式,然而在和对方写的C#的程序对接时发现无法实现互相加解密。

解决方法

其实原因很简单,犯了个低级错误,AES128-ecb加密密钥采用了256位(32字节)的形式,而AES加密的位数是和密钥长度挂钩的,然后若是用256位的密钥则C#中相当于用AES256-ecb进行加密了,而c中因为调用的函数接口的原因,key截断为了128位还是使用的128位加密,这时候不同库间加解密通信会失败。因此AES128的密钥长度不要超过128位。

/*************************************************************************
    > File Name: test_aes.c
    > Author: Filon
    > Created Time: Wed 06 Dec 2017 05:23:08 PM CST
 ************************************************************************/

#include<stdio.h>
#include<stdint.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<openssl/aes.h>

#define LEN 512


static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                '4', '5', '6', '7', '8', '9', '+', '/'};
static char *decoding_table = NULL;
static int mod_table[] = {0, 2, 1};


void build_decoding_table(void) {

    decoding_table = malloc(256);

    for (int i = 0; i < 64; i++)
        decoding_table[(unsigned char) encoding_table[i]] = i;
}

void base64_cleanup(void) {
    free(decoding_table);
}


size_t base64_encode(const unsigned char *data,
                    size_t input_length,
                    unsigned char *encoded_data) {
    size_t output_length;
    output_length = 4 * ((input_length + 2) / 3);

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
        uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < mod_table[input_length % 3]; i++)
        encoded_data[output_length - 1 - i] = '=';

    return output_length;
}


size_t base64_decode(const unsigned char *data,
                             size_t input_length,
                             unsigned char *decoded_data) {

    size_t output_length;
    if (decoding_table == NULL) build_decoding_table();

    if (input_length % 4 != 0) return -1;

    output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (output_length)--;
    if (data[input_length - 2] == '=') (output_length)--;

    for (int i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
    return output_length;
}



int main()
{
    int len = LEN, out_len = 0;
    unsigned char *raw_in = "0123456789abcdef0123456789abcdef";
    unsigned char input[LEN];
    unsigned char *userKey= "fedcba9876543210fedcba9876543210";
//  unsigned char *userKey = "fedcba9876543210";
    unsigned char out[LEN];
    unsigned char out_b64[LEN];
    unsigned char out_b64_src[LEN];
    unsigned char plain[LEN];
    AES_KEY aes_enc_ctx;

    memset(input, 0, LEN); 
    memset(out, 0, LEN);
    memset(out_b64, 0, LEN);
    memset(out_b64_src, 0, LEN);
    memset(plain, 0, LEN);

    build_decoding_table();

#define PCKS7 

#ifdef PCKS7 
    // pcks7padding
    int orglen = strlen(raw_in);
    len = (orglen + 15)/16 * 16;
    memset(input, len - orglen, sizeof(input));
    memcpy(input, raw_in, orglen);
#else 
    //zeropadding
    len = (strlen(raw_in) + 15)/16 * 16;
    strcpy(input, raw_in);
#endif
    printf("input = \n%s\n\n", input);

    //encrypt
    AES_set_encrypt_key(userKey, 128, &aes_enc_ctx);//这一步设置的密钥的长度位128,长则截断,短则用0补齐
    for(int i = 0; i < len/16; ++i) {
        AES_encrypt(input + i*16, out + i*16, &aes_enc_ctx);
    }
    printf("out = \n");
    for(int i=0; i < len; ++i)
    {
        printf("%02x", out[i]);
        if ((i+1)%16 == 0)
            puts("");
    }
    puts("");

    //b64encode
    out_len = base64_encode(out, len, out_b64);
    printf("out_b64 = \n%s\n\n", out_b64);

    //b64decode
    len = base64_decode(out_b64, out_len, out_b64_src);
    printf("out_b64_src = \n");
    for(int i=0; i < len; ++i)
    {
        printf("%02x", out_b64_src[i]);
        if ((i+1)%16 == 0)
            puts("");
    }
    puts("");

    //decrypt
    AES_set_decrypt_key(userKey, 128, &aes_enc_ctx);
    for(int i = 0; i < len/16; ++i) {   
        AES_decrypt(out_b64_src + i*16, plain + i*16, &aes_enc_ctx);
    }
    printf("plain = \n%s\n\n\n", plain);

    base64_cleanup();
    return 0;
}

图一
会打印加密后的16进制数据和转码成base64编码的数据。

代码中采用的AES_encrypt()函数AES_decrypt() 函数就是默认的电子密码本(ecb:electronic book),还有可以看到截断密钥的部分,实现:Link

另外,上面连接的中源码,为了加快加解密速度,是在文件中保存了一系列的表,加密过程中查表来代替计算,其原理看百科更好点。
其实还可以用下面的加密函数来替代AES_encrypt()函数AES_decrypt()这样代码的可读性更高点

void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
                     const AES_KEY *key, const int enc)
{

    assert(in && out && key);
    assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));

    if (AES_ENCRYPT == enc)
        AES_encrypt(in, out, key);
    else
        AES_decrypt(in, out, key);
}

PS: 编译的时候别忘了链接crypto的库,类似于:gcc test_aes.c -o test_aes -lcrypto

猜你喜欢

转载自blog.csdn.net/u014436243/article/details/78747620
今日推荐