c++ - 在 libgcrypt 中用 Crypto++ 解密加密数据的步骤

标签 c++ crypto++ libgcrypt

由于目标平台的 C 语言限制,我需要在 libgcrypt 中通过 Crypto++ 解密加密数据。所以我决定使用 libgcrypt,因为它支持 AES128 和 GCM 模式。

在 Crypto++ 中,数据是这样加密的:

std::string encrypt_data(const std::string &data,
                         const std::vector<unsigned char> &iv,
                         const std::vector<unsigned char> &key)
{
    CryptoPP::GCM<CryptoPP::AES>::Encryption encryptor;
    encryptor.SetKeyWithIV(&key[0], key.size(), &iv[0]);

    std::string ciphertext;
    CryptoPP::StringSource ss( data, true,
                            new CryptoPP::AuthenticatedEncryptionFilter(
                                encryptor,
                                new CryptoPP::StringSink(ciphertext)
                                )
                            );

    return ciphertext;
}

并以这种方式成功解密:

std::string decrypt_data(const std::string &data,
                         const std::vector<unsigned char> &iv,
                         const std::vector<unsigned char> &key)
{
    CryptoPP::GCM<CryptoPP::AES>::Decryption decryptor;
    decryptor.SetKeyWithIV(&key[0], key.size(), &iv[0]);

    std::string recovered;
    CryptoPP::StringSource ss( data, true,
                            new CryptoPP::AuthenticatedDecryptionFilter(
                                decryptor,
                                new CryptoPP::StringSink( recovered )
                                )
                            );

    return recovered;
}                       

但是当我尝试通过以下步骤使用 libgcrypt 解码 ciphertext 时,解码数据是错误的:

  1. gcry_cipher_open()
  2. gcry_cipher_setkey()
  3. gcry_cipher_setiv()
  4. 将密文和认证标签分开
  5. gcry_cipher_decrypt(密文)
  6. gcry_cipher_checktag(认证标签)

我是否遗漏了复制 Crypto++ 解码过程的任何步骤?

Gcrypt解密代码(预期输出Decrypted cipher = password):

#include <stdio.h>
#include <stdlib.h>
#include <gcrypt.h>

static unsigned char const aesSymKey[] = { 0x38, 0xb4, 0x8f, 0x1f, 0xcd, 0x63, 0xef, 0x32, 0xc5, 0xd1, 0x3f, 0x52, 0xbc, 0x4f, 0x5b, 0x24 };

static unsigned char const aesIV[] = { 0xE4, 0xEF, 0xC8, 0x08, 0xEB, 0xB8, 0x69, 0x95, 0xF3, 0x44, 0x6C, 0xE9, 0x15, 0xE4, 0x99, 0x7E };

static unsigned char const aesPass[] = { 0xda, 0x84, 0x3f, 0x01, 0xa0, 0x14, 0xfd, 0x85 };

static unsigned char const aesTag[] = { 0xdf, 0x5f, 0x9f, 0xe2, 0x9d, 0x7e, 0xc3, 0xdf, 0x7a, 0x1e, 0x59, 0xd8, 0xe6, 0x61, 0xf7, 0x7e };

#define GCRY_CIPHER GCRY_CIPHER_AES128
#define GCRY_MODE GCRY_CIPHER_MODE_GCM

int main(){
    gcry_error_t     gcryError;
    gcry_cipher_hd_t gcryCipherHd;

    if (!gcry_check_version(GCRYPT_VERSION))
     {
       fputs("libgcrypt version mismatch\n", stderr);
       exit(2);
     }

    gcry_control(GCRYCTL_DISABLE_SECMEM, 0);

    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

    if(!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
    {
        fputs("libgcrypt has not been initialized\n", stderr);
        abort();
    }

    size_t keyLength = gcry_cipher_get_algo_keylen(GCRY_CIPHER);
    size_t blkLength = gcry_cipher_get_algo_blklen(GCRY_CIPHER);

    char * outBuffer = malloc(blkLength);

    gcryError = gcry_cipher_open(
        &gcryCipherHd, // gcry_cipher_hd_t *
        GCRY_CIPHER,   // int
        GCRY_MODE,     // int
        0);            // unsigned int
    if (gcryError)
    {
        printf("gcry_cipher_open failed:  %s/%s\n",
               gcry_strsource(gcryError),
               gcry_strerror(gcryError));
        return;
    }

    gcryError = gcry_cipher_setkey(gcryCipherHd, aesSymKey, keyLength);
    if (gcryError)
    {
        printf("gcry_cipher_setkey failed:  %s/%s\n",
               gcry_strsource(gcryError),
               gcry_strerror(gcryError));
        return;
    }

    gcryError = gcry_cipher_setiv(gcryCipherHd, aesIV, blkLength);
    if (gcryError)
    {
        printf("gcry_cipher_setiv failed:  %s/%s\n",
               gcry_strsource(gcryError),
               gcry_strerror(gcryError));
        return;
    }

    gcryError = gcry_cipher_decrypt(
        gcryCipherHd, // gcry_cipher_hd_t
        outBuffer,    // void *
        blkLength,    // size_t
        aesPass,      // const void *
        8);           // size_t
    if (gcryError)
    {
        printf("gcry_cipher_decrypt failed:  %s/%s\n",
               gcry_strsource(gcryError),
               gcry_strerror(gcryError));
        return;
    }

    gcryError = gcry_cipher_checktag(
        gcryCipherHd,
        aesTag,
        blkLength);
    if (gcryError)
    {
        printf("gcry_cipher_checktag failed:  %s/%s\n",
               gcry_strsource(gcryError),
               gcry_strerror(gcryError));
        return;
    }

    printf("Decrypted cipher = %s\n", outBuffer);

    // clean up after ourselves
    gcry_cipher_close(gcryCipherHd);
    free(outBuffer);

    return 0;
}

编辑:明确地说,我正在搜索的解密步骤是针对上面显示的 Crypto++ 加密函数的 ciphertext 输出; encrypt_data()。所以我不会接受任何不能应用于成功解密ciphertext的答案。

最佳答案

答案的第 2 部分(共 2 部分)。这是 Gcrpyt 解密器。它使用第 1 部分中的参数。

在下面的代码中,调用gcry_cipher_decrypt 获取解密文本。但是我不知道如何从库中获取解密文本的大小。这对 GCM 模式无关紧要,但对其他模式(如 CBC)很重要。请参阅此 Stack Overflow 问题:Determine size of decrypted data from gcry_cipher_decrypt? .

ROUNDUP 用于向上舍入到密码 block 大小的倍数。我在 Working with Ciphers 读到这是对解密缓冲区的要求,但在这里可能不适用。我把它留在原地是因为“一切正常”,但如果它困扰你,你应该进一步打开它。

如果您在 AEAAD 预处理器宏上打开旋钮,那么您将需要使用 Crypto++ 加密例程生成新参数。

/* gcc -g3 -O1 -Wall -Wextra -std=c99 gcm-gcrypt-decrypt.c /usr/local/lib/libgcrypt.a /usr/local/lib/libgpg-error.a -o gcm-gcrypt-decrypt.exe */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <gcrypt.h>

typedef unsigned char byte;

/* All of this was generated in Crypto++ */
const byte key[] =  { 0x73,0x12,0xBB,0xDB,0x86,0x73,0x65,0xF7,0x68,0x7D,0xE9,0x2B,0xF8,0xEE,0x66,0xF1 };
const byte iv[] =  { 0x8C,0x70,0x54,0x17,0xD6,0xD9,0x7B,0x18,0x39,0xDC,0x5B,0xBC,0x21,0xDF,0x30,0x74 };
const byte plain[] =  { 0x4E,0x6F,0x77,0x20,0x69,0x73,0x20,0x74,0x68,0x65,0x20,0x74,0x69,0x6D,0x65,0x20,0x66,0x6F,0x72,0x20,0x61,0x6C,0x6C,0x20,0x67,0x6F,0x6F,0x64,0x20,0x6D,0x65,0x6E,0x20,0x74,0x6F,0x20,0x63,0x6F,0x6D,0x65,0x20,0x74,0x6F,0x20,0x74,0x68,0x65,0x20,0x61,0x69,0x64,0x65,0x20,0x6F,0x66,0x20,0x74,0x68,0x65,0x20,0x63,0x6F,0x75,0x6E,0x74,0x72,0x79,0x2E,0x00 };
const byte aad[] =  { 0x41,0x74,0x74,0x61,0x63,0x6B,0x20,0x61,0x74,0x20,0x64,0x61,0x77,0x6E,0x21,0x00 };
const byte cipher[] =  { 0xE8,0x0E,0xEA,0x10,0x32,0x26,0x7D,0xD1,0x75,0xF3,0x33,0x0F,0x30,0xBB,0x36,0xFB,0x3F,0x95,0x24,0x31,0x90,0xD2,0x2C,0xB1,0x34,0x5B,0x69,0x42,0x1E,0x98,0xC4,0x65,0x3B,0x06,0x5D,0x45,0xB6,0xC7,0x7E,0x26,0x7E,0xBC,0xFF,0xB7,0x7F,0xF4,0x11,0xF8,0xF3,0x8B,0x19,0x08,0xE6,0xAE,0x36,0x44,0xEF,0x3F,0xA6,0xC3,0xAE,0x34,0x08,0xB9,0x33,0xD3,0x33,0x63,0x46 };
const byte tag[] =  { 0x00,0xAE,0xDC,0x12,0x55,0xF8,0x87,0xB5,0x10,0x75,0x20,0xB5,0x94,0xCA,0x91,0xDF };

#define COUNTOF(x) ( sizeof(x) / sizeof(x[0]) )
#define ROUNDUP(x, b) ( (x) ? (((x) + (b - 1)) / b) * b : b)
byte recovered[ ROUNDUP(COUNTOF(cipher), 16) ];

#define GCRY_CIPHER GCRY_CIPHER_AES128
#define GCRY_MODE GCRY_CIPHER_MODE_GCM

#define AE 1
#define AAD 1

int main(){
    gcry_error_t     err;
    gcry_cipher_hd_t handle;
    memset(recovered, 0x00, COUNTOF(recovered));

    fprintf(stdout, "Plaintext size: %d\n", (int)COUNTOF(plain));
    fprintf(stdout, "Ciphertext size: %d\n", (int)COUNTOF(cipher));
    fprintf(stdout, "Recovered size: %d\n", (int)COUNTOF(recovered));

    assert(COUNTOF(key) == gcry_cipher_get_algo_keylen(GCRY_CIPHER));
    assert(COUNTOF(iv) == gcry_cipher_get_algo_blklen(GCRY_CIPHER));
    assert(COUNTOF(recovered) % gcry_cipher_get_algo_blklen(GCRY_CIPHER) == 0);

    if (!gcry_check_version(GCRYPT_VERSION))
     {
       fputs("libgcrypt version mismatch\n", stderr);
       exit(2);
     }

    gcry_control(GCRYCTL_DISABLE_SECMEM, 0);

    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

    if(!gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
    {
        fputs("libgcrypt has not been initialized\n", stderr);
        abort();
    }

    err = gcry_cipher_open(
        &handle,           // gcry_cipher_hd_t *
        GCRY_CIPHER,       // int
        GCRY_MODE,         // int
        0);                // unsigned int
    if (err)
    {
        printf("gcry_cipher_open failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }

    err = gcry_cipher_setkey(handle, key, COUNTOF(key));
    if (err)
    {
        printf("gcry_cipher_setkey failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }

    err = gcry_cipher_setiv(handle, iv, COUNTOF(iv));
    if (err)
    {
        printf("gcry_cipher_setiv failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }

#if defined(AAD)
    err = gcry_cipher_authenticate(
        handle,         // gcry_cipher_hd_t
        aad,            // void *
        COUNTOF(aad));  // size_t
    if (err)
    {
        printf("gcry_cipher_authenticate failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }
#endif

#if defined(AE)
    err = gcry_cipher_decrypt(
        handle,             // gcry_cipher_hd_t
        recovered,          // void *
        COUNTOF(recovered), // size_t
        cipher,             // const void *
        COUNTOF(cipher));   // size_t
    if (err)
    {
        printf("gcry_cipher_decrypt failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }
#endif

    err = gcry_cipher_checktag(
        handle,
        tag,
        COUNTOF(tag));
    if (err)
    {
        printf("gcry_cipher_checktag failed:  %s/%s\n",
               gcry_strsource(err),
               gcry_strerror(err));
        return 1;
    }

#if defined(AE)
    fprintf(stdout, "Decrypted = %s\n", recovered);
#endif

#if defined(AAD)
    fprintf(stdout, "Additional data = %s\n", (char*)aad);
#endif

    gcry_cipher_close(handle);

    return 0;
}

它产生的输出类似于:

$ ./gcm-gcrypt-decrypt.exe
Plaintext size: 69
Ciphertext size: 69
Recovered size: 80
Decrypted = Now is the time for all good men to come to the aide of the country.
Additional data = Attack at dawn!

关于c++ - 在 libgcrypt 中用 Crypto++ 解密加密数据的步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756446/

相关文章:

linux - 如何修复此 libgcrypt 交叉编译错误?

java - 使用 BouncyCaSTLe (java) 和 Gcrypt (C) 加密给出不同的结果

c++ - 在我调用 delete 之后仍然可以访问值,c++

c# - c++/c# 命名管道中的问题

c++ - 为什么我需要在这个函数中使用指向指针的指针而不是其他任何地方?

crypto++ - 从内存加载 RSA PKCS#1 私钥?

c++ - 来自 OpenSSL 的 BN_bin2bn 是否与采用字节数组的 Crypto++ Integer 的构造函数相同?

c++ - 将 bool 值返回到 C- 环境

c++ - Crypto++ 的 SecByteBlock 类的优点

c - 在 C 中使用 libgcrypt 导出 key