openssl 3des with c++

openssl 3des with c++

本文关键字:c++ with 3des openssl      更新时间:2023-10-16

我想使用C++中的openssl库来解密数据。

我有键和IV和编码的base64字符串。

我无法通过文档完成,所有解密方法(openssl/des.h(中的所有解密方法拿3键。

我设法通过以下python代码实现了结果。

from pyDes import *
import base64
key = base64.b64decode("****")
iv = base64.b64decode("***")
enc = base64.b64decode("******")
encryptor = triple_des(key, CBC, iv)
plain = encryptor.decrypt(enc)
print(plain.decode("utf-8"))

我想使用C 代码和OpenSSL库获得相同的结果。

3DES使用三个键。您正在使用的Python函数可能会从您通过的密钥参数中派生三个键,这可能分为三个部分。

要使用openSSL函数,您必须生成3个键,每个键具有8个字节(或3个字节键拆分(。

我调整了我在这里发现的代码,而不是CBC。但是,出于安全原因,您应该考虑使用CBC甚至AES加密而不是3DE。

该示例仅显示如何使用硬编码键使用DES_ecb3_encrypt函数。在最终解决方案中,您必须使用良好的RNG生成自己的密钥。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/des.h>
/* Triple DES key for Encryption and Decryption */
DES_cblock Key1 = { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
DES_cblock Key2 = { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 };
DES_cblock Key3 = { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33 };
DES_key_schedule SchKey1,SchKey2,SchKey3;
/* Print Encrypted and Decrypted data packets */
void print_data(const char *tittle, const void* data, int len);
int main()
{
    /* Input data to encrypt */
    DES_cblock input_data = {0x01, 0x02, 0x03, 0x04, 0x05, 0x6, 0x7, 0x8};
    /* Check for Weak key generation */
    if ( -2 == (DES_set_key_checked(&Key1, &SchKey1) || DES_set_key_checked(&Key2, &SchKey2) || DES_set_key_checked(&Key3, &SchKey3)))
    {
        printf(" Weak key ....n");
        return 1;
    }
    /* Buffers for Encryption and Decryption */
    DES_cblock cipher;
    DES_cblock text;
    /* Triple-DES ECB Encryption */
    DES_ecb3_encrypt(&input_data, &cipher, &SchKey1, &SchKey2, &SchKey3, DES_ENCRYPT);
    /* Triple-DES ECB Decryption */
    DES_ecb3_encrypt(&cipher, &text, &SchKey1, &SchKey2, &SchKey3, DES_DECRYPT);
    /* Printing and Verifying */
    print_data("n Original ", (const void*) input_data, sizeof(input_data));
    print_data("n Encrypted", (const void*) cipher, sizeof(input_data));
    print_data("n Decrypted", (const void*) text, sizeof(input_data));
    return 0;
}
void print_data(const char *tittle, const void* data, int len)
{
    printf("%s : ",tittle);
    const unsigned char * p = (const unsigned char*)data;
    int i = 0;
    for (; i<len;++i)
        printf("%02X ", *p++);
    printf("n");
}

openssl参考:

void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output, 
        DES_key_schedule *ks1, DES_key_schedule *ks2, 
        DES_key_schedule *ks3, int enc);

DES_ECB3_ENCRYPT((通过在欧洲央行模式下使用三键三键加密来加密输入块。这涉及使用KS1加密输入,用关键附表KS2解密,然后使用KS3进行加密。这种例程大大减少了DES蛮力破裂的机会,并且具有如果KS1,KS2和KS3相同,则相当于仅使用ECB模式和KS1作为键进行加密。