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

标签 c string encryption openssl

我无法使用解密的字符串。示例我想将解密的字符串复制到其他字符串。如果我尝试使用 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/

相关文章:

c - 将字符串文件读取到字符串数组

Java套接字通信——传输加密数据

c - 第一次体验结构。为什么会出现这种输出?

c - getc Vs getchar Vs Scanf 从标准输入读取一个字符

c - 在终端中出现错误“\365\277\357\376”

c# - 关于字符串实习和替代方案

string - 我怎么说,如果 label.text == 任何 Int

php - 如何正确存储 PBKDF2 密码哈希

带有敏感参数的 Python 配置文件

c - 程序执行输出