开发者

AES_ctr128_encrypt() "Segmentation fault" (OpenSSL)

开发者 https://www.devze.com 2023-03-27 17:37 出处:网络
i need to decrypt some cypherd text (aes 128 ctr) programming in C using openssl, since libraries version i\'m using don\'t support EVP for aes ctr i\'m tring to use AES_ctr128_encrypt(), but i get se

i need to decrypt some cypherd text (aes 128 ctr) programming in C using openssl, since libraries version i'm using don't support EVP for aes ctr i'm tring to use AES_ctr128_encrypt(), but i get segmentation fault, here's the code i'm using:

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

int chartoint(char car)开发者_运维知识库;
char * extochar(char * in, int inLen);

struct ctr_state { 
    unsigned char ivec[16];   
    unsigned int num; 
    unsigned char ecount[16]; 
}; 

void init_ctr(struct ctr_state *state, const unsigned char iv[16]){
    state->num = 0; 
    memset(state->ecount, 0, 16); 
    memcpy(state->ivec, iv, 16);
} 

void main(){
    unsigned char * cypher = extochar("874d6191b620e3261bef6864990db6ce",32);
    unsigned char * key = extochar("2b7e151628aed2a6abf7158809cf4f3c",32);
    unsigned char * iv = extochar("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",32);
    unsigned char out[256]; //more than needed
    AES_KEY aes_key;
    int msg_len = 16;
    struct ctr_state status; 

    if (!AES_set_encrypt_key(key, 16, &aes_key)){
        printf("key error"); 
        exit(-1);
    }

    init_ctr(&status, iv);

    AES_ctr128_encrypt(cypher, out, msg_len, &aes_key, status.ivec, status.ecount, &status.num);
//expected plaintext: "6bc1bee22e409f96e93d7e117393172a"
}

segmentation fault is on istruction AES_ctr128_encrypt(), the last one, while i'm expecting "6bc1bee22e409f96e93d7e117393172a" as plaintext (using printf("%02x", var[i]) to printf it)


Your AES key is 256 bits long. You tell AES_set_encrypt_key that it's 16 bits. And then you pass the key to AES_ctr 128 _encrypt. Your code would work a lot better if all three of those numbers were the same.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号