我无法使用解密的字符串。示例我想将解密的字符串复制到其他字符串。如果我尝试使用strcpy进行复制,我会在decrypt语句中出错。如果我只打印解密的字符串,我工作正常。我得到了正确的decypted字符串。但是当我尝试将解密的字符串用于某种目的时,问题就开始了。可能是什么问题? 我正在使用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);
}
答案 0 :(得分:0)
如果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;
}