gpt4 book ai didi

c - 如何将 Unsigned char* 字符串用作普通 char* 字符串

转载 作者:行者123 更新时间:2023-11-30 16:55:16 25 4
gpt4 key购买 nike

我无法使用解密的字符串。示例我想将解密的字符串复制到其他字符串。如果我尝试使用 strcpy 进行复制,则会在解密语句中收到错误。如果我只打印解密的字符串,我工作得很好。我得到了正确的解密字符串。但是当我尝试将解密的字符串用于某种目的时,问题就开始了。可能是什么问题?我正在使用openssl加密和解密。

 void kdcStep3(connection_info *connection, char msg[128]) {

printf(KCYN " %s" RESET "\n",connection->username);

char myUsername[50];
char myPassword[50];
puts(msg);

strcpy(myUsername, strtok(connection->username, " "));
strcpy(myPassword, strtok(NULL, " "));
puts(myPassword);

/* A 256 bit key */
unsigned char *key = (unsigned char *)myPassword;

/* A 128 bit IV */
unsigned char *iv = (unsigned char *)"01234567890123456";


/* Buffer for ciphertext. Ensure the buffer is long enough for the
* ciphertext which may be longer than the plaintext, dependant on the
* algorithm and mode
*/
unsigned char ciphertext[128];

/* Buffer for the decrypted text */
unsigned char decryptedtext[128];

int decryptedtext_len, ciphertext_len;

/* Initialise the library */
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
OPENSSL_config(NULL);

/* Encrypt the plaintext */
ciphertext_len = strlen(msg);

/* Do something useful with the ciphertext here */
printf("Ciphertext is:\n");
//BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);

/* Decrypt the ciphertext */
decryptedtext_len = decrypt(msg, ciphertext_len, key, iv,
decryptedtext);

/* Add a NULL terminator. We are expecting printable text */
decryptedtext[decryptedtext_len] = '\0';

/* Show the decrypted text */
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);

/* Clean up */
EVP_cleanup();
ERR_free_strings();


puts((const char*)decryptedtext);


}

最佳答案

如果puts正确打印解密的文本,则意味着它已被正确处理。无法使用它必须来自于您将其传递回调用者的方式。由于 decryptedtext 缓冲区是您的函数的本地缓冲区,因此您不能简单地将其返回给调用者。您需要将其复制到已进行 malloc 编辑的内存块中,如下所示

unsigned char *kdcStep3(connection_info *connection, char msg[128]) {
...
unsigned char *res = malloc(decryptedtext_len+1);
memcpy(res, decryptedtext, decryptedtext_len);
res[decryptedtext_len] = '\0';
return res;
}

或更改 API 以将 decryptedtext 作为参数,如下所示:

size_t kdcStep3(connection_info *connection, char msg[128], unsigned char decryptedtext[128]) {
...
return decryptedtext_len;
}

关于c - 如何将 Unsigned char* 字符串用作普通 char* 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40342066/

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