openssh ecdsa sign verify but is wrong - c

I've written some C code witch should sign an hash.
It seems to work fine; sign, generate public key and verify correctly.
but then using the sign result into another know-working code give me a key verification error (the sign is used over a bitcoin transaction)
Testing code is working fine, it can sign and verify, also used a third library (bitcoin's own implementation) and again it works fine.
So there is a bug in how I use OpenSSH but I can't find it. Any help appreciated, thanks.
Here the sign generator compiled with gcc -g -lssl -lcrypto
#include <openssl/ec.h> // for EC_GROUP_new_by_curve_name, EC_GROUP_free, EC_KEY_new, EC_KEY_set_group, EC_KEY_generate_key, EC_KEY_free
#include <openssl/ecdsa.h> // for ECDSA_do_sign, ECDSA_do_verify
#include <openssl/obj_mac.h> // for NID_secp192k1
#include <openssl/sha.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
int create_signature (uint8_t * hash, int len)
{
/*
/ */ convert priv key from hexadecimal to BIGNUM
uint8_t hex[] =
{ 0x0C, 0xAE, 0xCF, 0x01, 0xD7, 0x41, 0x02, 0xA2, 0x8A, 0xED, 0x6A, 0x64,
0xDC, 0xF1, 0xCF, 0x7B, 0x0E, 0x41, 0xC4, 0xDD, 0x6C, 0x62, 0xF7, 0x0F, 0x46, 0xFE,
0xBD, 0xC3, 0x25, 0x14, 0xF0, 0xBD };*/
EC_KEY *eckey = NULL;
EC_POINT *pub_key = NULL;
const EC_GROUP *group = NULL;
BIGNUM start;
BIGNUM *res;
BN_CTX *ctx;
BN_init(&start);
ctx = BN_CTX_new(); // ctx is an optional buffer to save time from allocating and deallocating memory whenever required
res = &start;
BN_hex2bn(&res,"0caecf01d74102a28aed6a64dcf1cf7b0e41c4dd6c62f70f46febdc32514f0bd");
eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
group = EC_KEY_get0_group(eckey);
EC_KEY_set_private_key(eckey, res);
int function_status = -1;
if (NULL == eckey)
{
printf ("\nFailed to create new EC Key\n");
function_status = -1;
} else {
unsigned int nSize = ECDSA_size(eckey);
uint8_t ris[nSize];
if (!ECDSA_sign(0, hash, sizeof(hash), ris, &nSize, eckey)){
printf ("\nFailed to generate EC Signature\n");
} else {
printf ("\nOK to generate EC Signature len: %d \n", nSize);
for (int i=0;i<nSize; i++) {
printf ("%02X", ris[i]);
}
{
pub_key = EC_POINT_new(group);
if (!EC_POINT_mul(group, pub_key, res, NULL, NULL, ctx))
printf("Error at EC_POINT_mul.\n");
EC_KEY_set_public_key(eckey, pub_key);
char *cc = EC_POINT_point2hex(group, pub_key, 4, ctx);
char *c=cc;
int i;
printf("\npublic key:");
for (i=0; i<130; i++) // 1 byte 0x42, 32 bytes for X coordinate, 32 bytes for Y coordinate
{
printf("%c", *c++);
}
free(cc);
}
int verify_status = ECDSA_verify(0, hash, sizeof(hash), ris, nSize, eckey);
const int verify_success = 1;
if (verify_success != verify_status)
{
printf("\nFailed to verify EC Signature\n");
function_status = -1;
} else {
printf("\nVerifed EC Signature\n");
function_status = 1;
}
}
EC_KEY_free (eckey);
}
return function_status;
}
int main() {
uint8_t double_hash[] = { 0x5f,0xda,0x68,0x72,0x9a,0x63,0x12,0xe1,0x7e,0x64,0x1e,0x9a,0x49,0xfa,0xc2,0xa4,0xa6,0xa6,0x80,0x12,0x66,0x10,0xaf,0x57,0x3c,0xaa,0xb2,0x70,0xd2,0x32,0xf8,0x50 };
printf ("\nhash len: %d \n", sizeof(double_hash));
create_signature( double_hash, sizeof(double_hash) );
}

Related

Getting different encryption strings between openssl CLI and C codeHello

I've been playing with openssl and am trying to write a simple program in C for encrypting a string. I'm trying to replicate the following command to encrypt the string "test" and then see the encrypted version using a given key and IV and AES-CBC-128:
echo test | openssl enc -e -aes-128-cbc -nosalt -K 5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a -iv 00000000000000000000000000000000 | xxd
and this returns the encrypted string in hex of
a63b e13d 47a5 b94c c1cb 466e 28af 19d8
I'm trying to replicate this in C with the following:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
int main() {
AES_KEY aes;
unsigned char* input_string = "test";
unsigned char* encrypt_string;
unsigned int len;
unsigned char key[] = {0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A,
0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0x5A};
unsigned char iv[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint32_t result;
result = AES_set_encrypt_key(key, 128, &aes);
if (result < 0) {
fprintf(stderr, "Unable to set encryption key in AES\n");
printf("%i", result);
exit(-1);
}
// set the encryption length
len = 0;
if ((strlen("test") + 1) % AES_BLOCK_SIZE == 0) {
len = strlen("test") + 1;
} else {
len = ((strlen("test") + 1) / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
}
encrypt_string = (unsigned char*)calloc(len, sizeof(unsigned char));
AES_cbc_encrypt(input_string, encrypt_string, 128, &aes, iv , AES_ENCRYPT);
printf("encrypted string = ");
for (int i=0; i<len; ++i) {
printf("%02X ", encrypt_string[i]);
}
printf("\n");
return 0;
}
and this returns the encrypted string as
encrypted string = C2 5D 07 2D D5 EC DB 94 3B FE 31 9F 51 DE EE 93
which doesn't match what I get from the CLI. What am I missing here that causing these not to match?

tiny-aes-c AES CTR 128 cuts off decrypted string in some cases

I've been trying to use the AES CTR 128 from tiny-aes-c (https://github.com/kokke/tiny-AES-c) to encrypt a randomly generated token, and it works, but not all the time. In some cases the retrieved string after encrypting and decrypting is cut off at some point. Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "token_auth.h"
#include "aes.h"
uint8_t * create_token() {
static char charset[] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
uint8_t *token = malloc(sizeof(uint8_t) * (TOKEN_LENGTH + 1));
int i = 0;
srand ( time(NULL) );
for (i = 0; i < TOKEN_LENGTH; i++) {
int pos = rand() % (int)(strlen(charset) - 1);
token[i] = (int) charset[pos] - 0;
}
token[TOKEN_LENGTH] = 0;
return token;
}
int main() {
uint8_t key[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
uint8_t iv[16] = { 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 };
uint8_t *in = create_token();
printf("\nInput: %s\nSize: %d", (char *) in, strlen((char *) in));
struct AES_ctx ctx;
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, in, strlen((char *) in));
AES_init_ctx_iv(&ctx, key, iv);
AES_CTR_xcrypt_buffer(&ctx, in, strlen((char *) in));
printf("\nDEC: %s\n", (char *) in);
return 0;
}
TOKEN_LENGTH is 128. As an example of the behavior, the string NM5DlWyYInbeNtEWhBxGCdEjHSv2I6FzTMffJNgudrL2UsYe6zVJMA3wvAyhHeQD18UMXckcF8gBAfPGQNqGqwdW9MgS39w7huVfIgtoqJ212SKSIdBaJP9VErOJAmQT comes out NM5DlWyYInbeNtEWhBxGCdEjHSv2 after being encrypted and decrypted. I'm not really good at C, so it might just well be a problem with something else I've done, but at this point I'm lost. Any ideas? Thanks in advance.
The first call to AES_CTR_xcrypt_buffer encrypts the buffer in place in CTR mode.
The buffer still has the same size (128 in your case), but can contain NUL bytes.
The strlen call in the second call of AES_CTR_xcrypt_buffer for decryption can therefore result in a length < 128 if the buffer contains a NUL byte.
By the way: It works in cases where the encryption does not result in a NUL byte in the buffer.
So if you call it with TOKEN_LENGTH as the length parameter decryption will give the original string again:
AES_CTR_xcrypt_buffer(&ctx, in, TOKEN_LENGTH);

How to correctly convert TAG value to the right format so that to Verify HMAC?

I'm working on HMAC generation and verifying to check data integrity. I can correctly generate the MAC value but when sending it through socket to another program for verification, I faced with formatting mismatch. I appreciate your support. Thanks.
unsigned char* MAC(unsigned char* key,unsigned char* message)
{
unsigned char* result;
unsigned int result_len = 32;
int i;
result = (unsigned char*) malloc(sizeof(char) * result_len);
result = HMAC(EVP_sha256 (), key , strlen (key), message , strlen(message) , NULL, NULL);
return result;
}
int verifyMAC(unsigned char* key,unsigned char* message, unsigned char* receivedTag)
{
printf("\n\n ==================== MAC Verification ==================\n\n");
unsigned char* newHash; // newly generated hash value
unsigned int newHash_len = 32;
int i,flag=0;
newHash = (unsigned char*) malloc(sizeof(char) * newHash_len);
newHash = HMAC(EVP_sha256 (), key , strlen (key), message , strlen(message) , NULL, NULL);
for (i=0; i!=newHash_len; i++)
{
if (receivedTag[i]!=newHash[i])
{
printf("DATA MISMATCH: Found %02X instead of %02X at index %d!\n", newHash[i], receivedTag[i], i);
break;
}
}
if (i==newHash_len)
{
printf("MAC verified!\n");
flag = 1;
}
return flag;
}
int main(int argc, char *argv[])
{
unsigned char* key = "1234567890";
unsigned char* message = (unsigned char*) "hello world";
....
}
Console result:
Hashed data: E4 5F 60 72 61 7C CE 5E 06 A9 5B E4 81 C4 33 51 02 3D 99 23 35 99 EA C9 FD AF FC 95 81 42 62 9A
==================== MAC Verification ==================
DATA MISMATCH: Found E4 instead of 65 at index 0!
ERROR: data is modified
I thought this problem was somewhat interesting so I went through the trouble to recreate the scenario. Maybe this is not even right. But a simple case of what I thought the problem is:
void main(int argc, char *argv[])
{
//the original hash
unsigned char newHash[] = {0xE4, 0x5F, 0x60, 0x72, 0x61, 0x7C, 0xCE, 0x5E, 0x06, 0xA9, 0x5B, 0xE4, 0x81, 0xC4, 0x33, 0x51,
0x02, 0x3D, 0x99, 0x23, 0x35, 0x99, 0xEA, 0xC9, 0xFD, 0xAF, 0xFC, 0x95, 0x81, 0x42, 0x62, 0x9A};
//what I think is recieved from the socket
unsigned char* receivedTag = "e45f6072617cce5e06a95be481c43351023d99233599eac9fdaffc958142629a";
for (int i=0; i!=32; i++)
{
if (receivedTag[i]!=newHash[i])
{
printf("DATA MISMATCH: Found %02X instead of %02X at index %d!\n", newHash[i], receivedTag[i], i);
break;
}
}
return;
}
and the output was
DATA MISMATCH: Found E4 instead of 65 at index 0!
So, I thought the solution would be to just convert the Hex array to string just like it was received from the socket.
Maybe this is not the most elegant of ways to do things. But a solution None the less.
char* hexStringToCharString(unsigned char hash[], int length);
void main(int argc, char *argv[])
{
//the original hash
unsigned char newHash[] = {0xE4, 0x5F, 0x60, 0x72, 0x61, 0x7C, 0xCE, 0x5E, 0x06, 0xA9, 0x5B, 0xE4, 0x81, 0xC4, 0x33, 0x51,
0x02, 0x3D, 0x99, 0x23, 0x35, 0x99, 0xEA, 0xC9, 0xFD, 0xAF, 0xFC, 0x95, 0x81, 0x42, 0x62, 0x9A};
//what I think is recieved from the socket
unsigned char* receivedTag = "e45f6072617cce5e06a95be481c43351023d99233599eac9fdaffc958142629a";
char *newString = hexStringToCharString(newHash, 32);
for (int i=0; i!=strlen(newString); i++)
{
if (receivedTag[i]!=newString[i])
{
printf("DATA MISMATCH: Found %02X instead of %02X at index %d!\n", newHash[i], receivedTag[i], i);
break;
}
}
free(newString);
printf("Yay\n");
return;
}
char* hexStringToCharString(unsigned char hash[], int length){
char temp[3];
//need length*2 characters which is 64 plus one for null!
char *theString = (char *)malloc(sizeof(char)*((length*2)+1));
strcpy(theString, "");
for(int i=0;i<length;i++){
sprintf(temp, "%02x", hash[i]);
strcat(theString, temp);
}
return theString;
}
The output in this case
Yay
So, Maybe this is entirely wrong. But if you find this solution needs editing then comment below.

Openssl: encryption output issue

I am encrypting 3gpp test data with openssl code in c language in linux platform.
i have taken example from stack over flow and tried.But in the final encryption output zeros's are not displayed.i need to encrypt with 128 bit key.
Thanks in advance.
#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>
#define u32 unsigned int
#define u8 unsigned char
#define bufferSize 16
struct ctr_state
{
unsigned char ivec[AES_BLOCK_SIZE];
unsigned int num;
unsigned char ecount[AES_BLOCK_SIZE];
};
AES_KEY key;
unsigned char indata[AES_BLOCK_SIZE];
unsigned char outdata[AES_BLOCK_SIZE];
unsigned char iv[AES_BLOCK_SIZE];
struct ctr_state state;
int init_ctr(struct ctr_state *state, const unsigned char iv[16])
{
/* aes_ctr128_encrypt requires 'num' and 'ecount' set to zero on the
* first call. */
state->num = 0;
memset(state->ecount, 0, AES_BLOCK_SIZE);
/* Initialise counter in 'ivec' to 0 */
memset(state->ivec + 8, 0, 8);
/* Copy IV into 'ivec' */
memcpy(state->ivec, iv, 8);
}
int main(int argc, char *argv[])
{
u8 key1[16] = {
0xd3,0xc5,0xd5,0x92,0x32,0x7f,0xb1,0x1c,
0x40,0x35,0xc6,0x68,0x0a,0xf8,0xc6,0xd1
};
u8 count[4] ={0x39,0x8a,0x59,0xb4};
u32 tempCount = 0;
u8 bearer = 0x15;
u8 dir =0x01,i;
u32 length = 253 ;
u8 indata[32] = {
0x98, 0x1b, 0xa6, 0x82, 0x4c, 0x1b, 0xfb, 0x1a,
0xb4, 0x85, 0x47, 0x20, 0x29, 0xb7, 0x1d, 0x80,
0x8c, 0xe3, 0x3e, 0x2c, 0xc3, 0xc0, 0xb5, 0xfc,
0x1f, 0x3d, 0xe8, 0xa6, 0xdc, 0x66, 0xb1, 0xf0
};
tempCount = htonl((count[0] | (count[1] << 8) | count[2]<< 16 | count[3] << 24)); /* Jyothi Added */
iv[0] = (tempCount >> 24) & 0xff ;
iv[1] = (tempCount >> 16) & 0xff ;
iv[2] = (tempCount >> 8) & 0xff;
iv[3] = tempCount & 0xff;
iv[4] = htonl((( (bearer << 27) | ((dir & 0x1) << 26))));
iv[5] = iv[6]= iv[7] = 0;
printf("iv=\n");
for(i=0;i<16;i++)
printf("%x",iv[i]);
printf("\n");
printf("key1=\n");
for(i=0;i<16;i++)
printf("%x",key1[i]);
printf("\n");
//Initializing the encryption KEY
if (AES_set_encrypt_key(key1, 128, &key) < 0)
{
fprintf(stderr, "Could not set decryption key.");
exit(1);
}
init_ctr(&state, iv);//Counter call
printf("state.ivec after call=\n");
for(i=0;i<16;i++)
printf("%x",state.ivec[i]);
printf("\n");
printf("indata=\n");
for(i=0;i<32;i++)
printf("%x",indata[i]);
printf("\n");
for(i=1;i<2;i++){
//Encrypting Blocks of 16 bytes
AES_ctr128_encrypt(indata, outdata,253, &key, state.ivec, state.ecount, &state.num);
printf("outdata\n");
for(i=0;i<32;i++)
printf("%x",outdata[i]);
printf("\n");
}
}
i am getting output as below.
iv=
398a59b4ac00000000000
key1=
d3c5d592327fb11c4035c668af8c6d1
state.ivec after call=
398a59b4ac00000000000
indata=
981ba6824c1bfb1ab485472029b71d808ce33e2cc3c0b5fc1f3de8a6dc66b1f0
outdata
e9fed8a63d15534d71df2bf3e82214b2ed7dad2f233dc3c22d7bdeeed8e78
algorithm has to generate key stream as below:
71e57e24 710ea81e 6398b52b da5f3f94 3eede9f6 11328620 231f3f1b 328b3f88
but instead it is generating final encryption output without zero's
final expected output is as below:
e9fed8a6 3d155304 d71df20b f3e82214 b20ed7da d2f233dc 3c22d7bd eeed8e78
Change your printf format string to require that each char is output as two hex digits - currently you're losing leading zeroes.
printf("%02x",outdata[i]);
The zero tells it to pad up to two digits using zeroes, the default would be spaces.

EVP_DecryptFinal_ex Error on OpenSSL

I am playing around with OpenSSL EVP routines for decryption using AES 128 cbc mode.
I use the test vectors specified at the NIST site to test my program.
The program seems to fail at EVP_DecryptFinal_ex routine.
Can anybody please tell me what is the problem?
Also how do I do the error checking here to find out why this routine fails?
UPDATED:
Please check the code below. I have added the encrypt and decrypt part. Encrypt works. But during the decryption, although the results of both match, the hexvalue of the cipher seems 80 bytes as opposed to the expected 64 bytes(mentioned in NIST) although the decryption works and the decrypted text matches the plaintext!
Can somebody clarify?
The expected ciphertext value should be:
cipher: 0000 76 49 ab ac 81 19 b2 46 ce e9 8e 9b 12 e9 19 7d
0010 50 86 cb 9b 50 72 19 ee 95 db 11 3a 91 76 78 b2
0020 73 be d6 b8 e3 c1 74 3b 71 16 e6 9e 22 22 95 16
0030 3f f1 ca a1 68 1f ac 09 12 0e ca 30 75 86 e1 a7
here is the code:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
int AES_BLOCK_SIZE;
int main(int argc, char **argv)
{
EVP_CIPHER_CTX en;
EVP_CIPHER_CTX de;
EVP_CIPHER_CTX_init(&en);
EVP_CIPHER_CTX_init(&de);
const EVP_CIPHER *cipher_type;
unsigned char *mode;
unsigned char *passkey, *passiv, *plaintxt;
int vector_len = 0;
char *plain;
char *plaintext;
unsigned char *ciphertext;
int olen, len;
int i =0;
//NIST VALUES TO CHECK
unsigned char iv[] =
{ 0x00, 0x01, 0x02, 0x03,
0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b,
0x0c, 0x0d, 0x0e, 0x0f, 0 };
unsigned char key[] =
{ 0x2b, 0x7e, 0x15, 0x16,
0x28, 0xae, 0xd2, 0xa6,
0xab, 0xf7, 0x15, 0x88,
0x09, 0xcf, 0x4f, 0x3c , 0 };
unsigned char input[] =
{ 0x6b, 0xc1, 0xbe, 0xe2,
0x2e, 0x40, 0x9f, 0x96,
0xe9, 0x3d, 0x7e, 0x11,
0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57,
0x1e, 0x03, 0xac, 0x9c,
0x9e, 0xb7, 0x6f, 0xac,
0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46,
0xa3, 0x5c, 0xe4, 0x11,
0xe5, 0xfb, 0xc1, 0x19,
0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45,
0xdf, 0x4f, 0x9b, 0x17,
0xad, 0x2b, 0x41, 0x7b,
0xe6, 0x6c, 0x37, 0x10, 0 };
printf("AES ALGORITHM FOR 128 bit CBC MODE\n");
cipher_type = EVP_aes_128_cbc();
AES_BLOCK_SIZE = 128;
passkey = key;
passiv = iv;
plain = input;
printf("iv=");
for(i = 0; i < sizeof iv; i++){
printf("%02x", iv[i]);
}
printf("\n");
printf("key=");
for(i = 0; i < sizeof key; i++){
printf("%02x", key[i]);
}
printf("\n");
printf("Initializing AES ALGORITHM FOR CBC MODE..\n");
EVP_EncryptInit_ex(&en, cipher_type, NULL, passkey, passiv);
EVP_DecryptInit_ex(&de, cipher_type, NULL, passkey, passiv);
olen = len = strlen(input)+1;
printf("len value before aes_encrypt \"%d\"\n", len);
int c_len = len + AES_BLOCK_SIZE - 1;
int f_len = 0;
ciphertext = (unsigned char *)malloc(c_len);
if(!EVP_EncryptInit_ex(&en, NULL, NULL, NULL, NULL)){
printf("ERROR in EVP_EncryptInit_ex \n");
return NULL;
}
if(!EVP_EncryptUpdate(&en, ciphertext, &c_len, plain, len)){
printf("ERROR in EVP_EncryptUpdate \n");
return NULL;
}
printf("strlen value of ciphertext after update \"%d\"\n", strlen(ciphertext));
if(!EVP_EncryptFinal_ex(&en, ciphertext+c_len, &f_len)){
printf("ERROR in EVP_EncryptFinal_ex \n");
return NULL;
}
printf("strlen value of ciphertext after final \"%d\"\n", strlen(ciphertext));
EVP_CIPHER_CTX_cleanup(&en);
len = c_len + f_len;
printf("len value after aes_encrypt \"%d\"\n", len);
len = strlen(ciphertext);
printf("strlen value of ciphertext after aes_encrypt \"%d\"\n", len);
int p_len = len;
f_len = 0;
plaintext = (unsigned char *)malloc(p_len);
//memset(plaintext,0,sizeof(plaintext));
if(!EVP_DecryptInit_ex(&de, NULL, NULL, NULL, NULL)){
printf("ERROR in EVP_DecryptInit_ex \n");
return NULL;
}
EVP_CIPHER_CTX_set_padding(&de, 0);
if(!EVP_DecryptUpdate(&de, plaintext, &p_len, ciphertext, len)){
printf("ERROR in EVP_DecryptUpdate\n");
return NULL;
}
if(!EVP_DecryptFinal_ex(&de, plaintext+p_len, &f_len)){
printf("ERROR in EVP_DecryptFinal_ex\n");
return NULL;
}
EVP_CIPHER_CTX_cleanup(&de);
len = p_len + f_len;
printf("Decrypted value = %s\n", plaintext);
printf("len value after aes_decrypt \"%d\"\n", len);
if (strncmp(plaintext, input, olen))
printf("FAIL: enc/dec failed for \"%s\"\n", input);
else
printf("OK: enc/dec ok for \"%s\"\n", plaintext); // \"%s\"\n
printf("OK: ciphertext is \"%s\"\n", ciphertext); // \"%s\"\n
printf("\n");
unsigned char *s3 = ciphertext;
printf("s3 =\n");
int nc = 0;
while(*s3 != '\0'){
printf("%02x", *s3);
s3++;
nc ++;
if(nc == 16){
printf("\n");
nc = 0;
}
}
printf("\n");
//printf("nc = %d\n", nc);
free(ciphertext);
free(plaintext);
return 0;
}
Just like you need to match the key and IV when you encrypt and decrypt, you also need to match the padding setting. The NIST tests are not padded. Here's an excerpt from the OpenSSL documentation:
EVP_DecryptInit_ex(),
EVP_DecryptUpdate() and
EVP_DecryptFinal_ex() are the
corresponding decryption operations.
EVP_DecryptFinal() will return an
error code if padding is enabled and
the final block is not correctly
formatted. The parameters and
restrictions are identical to the
encryption operations except that if
padding is enabled the decrypted data
buffer out passed to
EVP_DecryptUpdate() should have
sufficient room for (inl +
cipher_block_size) bytes unless the
cipher block size is 1 in which case
inl bytes is sufficient.
Searching that same page for "padding", you'll see the function EVP_CIPHER_CTX_set_padding:
EVP_CIPHER_CTX_set_padding() enables
or disables padding. By default
encryption operations are padded using
standard block padding and the padding
is checked and removed when
decrypting. If the pad parameter is
zero then no padding is performed, the
total amount of data encrypted or
decrypted must then be a multiple of
the block size or an error will occur.
So at some point after you call EVP_CIPHER_CTX_init and before you start decrypting, you need to do this:
EVP_CIPHER_CTX_set_padding(&de, 0);
To show the errors after an OpenSSL function fails, you can use:
ERR_print_errors_fp(stderr);
I had the same problem with EVP_DecryptFinal_ex routine. I've found out that you won't get the lenght of ciphertext by strlen(ciphertext) because the function strlen() returns the length of C string.
Ciphertext after encryption can contain '\0' characters which are considered end of C string, so you won't get the right length of ciphertext with function strlen().
Instead you should remember the length of ciphertext after encrypting. In your program you do it with c_len and f_len:
if(!EVP_EncryptUpdate(&en, ciphertext, &c_len, plain, len)){
printf("ERROR in EVP_EncryptUpdate \n");
return NULL;
}//Here you get length of ciphertext in c_len
printf("strlen value of ciphertext after update \"%d\"\n", strlen(ciphertext));
if(!EVP_EncryptFinal_ex(&en, ciphertext+c_len, &f_len)){
printf("ERROR in EVP_EncryptFinal_ex \n");
return NULL;
}//Here you get the rest of padded ciphertext in f_len
//This printf won't print out the real lengt of ciphertext you should put in (c_len+f_len)
printf("strlen value of ciphertext after final \"%d\"\n", strlen(ciphertext));
EVP_CIPHER_CTX_cleanup(&en);
len = c_len + f_len;//This is the real length of ciphertext
printf("len value after aes_encrypt \"%d\"\n", len);
len = strlen(ciphertext);//And here you rewrite it, delete this line and you should get it right
Another thing, when you what to print out cipher text don't use:
printf("OK: ciphertext is \"%s\"\n", ciphertext);
"%s" is also considered as C string and can print out just part of the whole ciphertext. Use instead:
int i = 0;
printf("\nCiphertext:");
for(i = 0; i < len; i++)//variable len is length of ciphertext memorized after encryption.
{printf("%c",ciphertext[i]);}

Resources