gpt4 book ai didi

Java DESede 加密,OpenSSL 等效

转载 作者:搜寻专家 更新时间:2023-10-31 01:16:32 25 4
gpt4 key购买 nike

我在 Java 中使用 DESede 加密,我想在 C++ 中使用 OpenSSL 的 API 进行相同的加密。

Java代码:

    String secretKey = "abcdefghijklmnopqrstuvwx";

byte[] bytes = secretKey.getBytes("UTF-8");
SecretKey key = new SecretKeySpec(bytes, "DESede");

Cipher ecipher = Cipher.getInstance("DESede");
ecipher.init(Cipher.ENCRYPT_MODE, key);

String input = "holahola1";

byte[] utf8 = input.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8); // Encrypt

输出:[94, -45, 64, -105, 99, -55, 99, -42, 95, 122, 72, 117, -119, 95, -43, 40]

C++代码:

    unsigned char intext[256], outtext[256];

memset(intext, 0, sizeof(intext));
memset(outtext, 0, sizeof(outtext));

char *output = (char *)outtext;
DES_key_schedule keyschedc1;
DES_key_schedule keyschedc2;
DES_key_schedule keyschedc3;
DES_cblock keyc1;
DES_cblock keyc2;
DES_cblock keyc3;

DES_string_to_key("abcdefgh", &keyc1);
DES_string_to_key("ijklmnop", &keyc2);
DES_string_to_key("qrstuvwx", &keyc3);
DES_set_key((DES_cblock *)keyc1, &keyschedc1);
DES_set_key((DES_cblock *)keyc2, &keyschedc2);
DES_set_key((DES_cblock *)keyc3, &keyschedc3);

strcpy((char *)intext, "holahola1");

for (int i=0; i<16; i += 8)
{
DES_ecb3_encrypt((DES_cblock *)(intext + i),
(DES_cblock *)(outtext + i),
&keyschedc1, &keyschedc2,
&keyschedc3,DES_ENCRYPT);
}

输出:[30 55 9 -58 -18 -65 -66 123 -32 72 30 110 120 69 101 -81]

怎么了?有人能帮我吗?谢谢!

最佳答案

我明白了。 Java DESede 加密,使用带 ecb 模式的三重 DES,并使用 PKCS#5 填充。因此,我使用 PKCS#5 填充我的文本,它解决了所有问题。

示例 C++ 代码:

unsigned char intext[256], outtext[256];

memset(intext, 0x07, sizeof(intext)); //PKCS#5 padding (See documentation)
memset(outtext, 0, sizeof(outtext));
char *output = (char *)outtext;

DES_key_schedule keyschedc1;
DES_key_schedule keyschedc2;
DES_key_schedule keyschedc3;
DES_cblock keyc1;
DES_cblock keyc2;
DES_cblock keyc3;

DES_set_key((DES_cblock *)"abcdefgh", &keyschedc1);
DES_set_key((DES_cblock *)"ijklmnop", &keyschedc2);
DES_set_key((DES_cblock *)"qrstuvwx", &keyschedc3);

strcpy((char *)intext, "holahola1");

for (int i=0; i<16; i += 8)
{
DES_ecb3_encrypt((DES_cblock *)(intext + i),
(DES_cblock *)(outtext + i),
&keyschedc1, &keyschedc2,
&keyschedc3,DES_ENCRYPT);
}

关于Java DESede 加密,OpenSSL 等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9038298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com