LINUX.ORG.RU

OpenSSL дает разные результаты при шифровке одинаковых данных одинаковым ключом по aes-256-cbc

 


0

1

Правильно ли я понимаю, что что зашифровав по алгоритму aes-256-cbc одни и те же данные одним и тем же ключом с одним и тем же вектором инициализации я должен ВСЕГДА получать одинаково-зашифрованные данные? Ну, то есть, это — чистая функция и не зависит от реализации?

Дивитесь:

$ cat key 
01234567890123456789012345678901

$ cat iv 
0123456789012345

$ echo -n "hello" | openssl enc -aes-256-cbc -K `cat key` -iv `cat iv` | base64
vRoZmUYh969H18TjJfldYw==

$ echo -n "hello" | ./aes_enc `cat key` `cat iv` | base64
VcyOES9/0YifXvnZKo8c4g==

$ cat aes_enc.c 
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
#include <stdio.h>

#define MAX_STR 1000

// compile:
// gcc aes_enc.c -lcrypto -o aes_enc

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
            unsigned char *iv, unsigned char *ciphertext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int ciphertext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
    ciphertext_len = len;

    /*
     * Finalise the encryption. Further ciphertext bytes may be written at
     * this stage.
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
        handleErrors();
    ciphertext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int main(int argc, char *argv[]) {
  unsigned char out[MAX_STR];
  unsigned char in[MAX_STR];

  int in_len = 0;

  in_len = fread( (unsigned char *)in , 1, MAX_STR, stdin );

  int out_len = encrypt( in, in_len, argv[1], argv[2], out);
  out[out_len] = '\0';

  printf("%s", out);

  return 0;
}


★★★★★

Собственно, это только минимальный пример.

Проблема в том что из си не расшифровывается то, что зашифрованно бинариком openssl. А вот то, что этими же сями зашифровано – расшифровывается.

Примеры с сайта openssl

pihter ★★★★★
() автор топика
Ответ на: комментарий от anonymous

Тога почему расшифровывается байт-в-байт то же, что и зашифровывалось?

pihter ★★★★★
() автор топика

ты в своей программе кодируешь вход как есть, а openssl их из 16-ричного строкового вида в бинарный конвертирует сначала

Harald ★★★★★
()
Ответ на: комментарий от Harald

это только ключа/вектора касается или и данных тоже?

pihter ★★★★★
() автор топика
Ответ на: комментарий от Harald

Сделал так:

$ cat aes_enc.c 
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>
#include <stdio.h>

#define MAX_STR 1000

// compile:
// gcc aes_enc.c -lcrypto -o aes_enc

static const unsigned char static_key[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

static const unsigned char static_iv[] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, const unsigned char *key,
            const unsigned char *iv, unsigned char *ciphertext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int ciphertext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new()))
        handleErrors();

    /*
     * Initialise the encryption operation. IMPORTANT - ensure you use a key
     * and IV size appropriate for your cipher
     * In this example we are using 256 bit AES (i.e. a 256 bit key). The
     * IV size for *most* modes is the same as the block size. For AES this
     * is 128 bits
     */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    /*
     * Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
    ciphertext_len = len;

    /*
     * Finalise the encryption. Further ciphertext bytes may be written at
     * this stage.
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
        handleErrors();
    ciphertext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int main(int argc, char *argv[]) {
  unsigned char out[MAX_STR];
  unsigned char in[MAX_STR];

  int in_len = fread( (unsigned char *)in , 1, MAX_STR, stdin );

  int out_len = encrypt( in, in_len, static_key, static_iv, out );
  out[out_len] = '\0';

  printf("%s", out);

  return 0;
}

$ cat key 
0000000000000000000000000000000000000000000000000000000000000000

$ cat iv
00000000000000000000000000000000

$ echo -n "hello" | openssl enc -aes-256-cbc -K `cat key` -iv `cat iv` | base64
wjXeJNI54DzI43fGBPymew==
$ echo -n "hello" | ./aes_enc | base64
wjXeJNI54DzI43fGBPymew==

Спасибо, товарищ Гарольд!

ЛОР — торт!

pihter ★★★★★
() автор топика
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.