如何将gcrypt库中gcry_cipher_encrypt的返回值复制到一个变量
C++, how to copy the return value of gcry_cipher_encrypt in gcrypt library to a variable?
在下面的代码中,它使用了gcry_cipher_encrypt。在代码的末尾,它以十六进制值字符串的形式输出encBuffer中的内容。我需要把它放在像char[], char*或string这样的变量中,然后使用它。
根据gcrypt, encBuffer的手册,函数的第二项应该是一个无符号char*类型的变量。我认为它应该指向一个无符号字符数组。但是当我这样做的时候:
for(int i = 0; i < txtLength-1;i++){
cout<<encBuffer[i];
}
得到大量代码。我怎么能得到可读的内容从encBuffer请?非常感谢。
#include <stdio.h>
#include <gcrypt.h>
int main () {
gcry_error_t gcryError;
gcry_cipher_hd_t gcryCipherHd;
size_t index;
char * salsaKey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // 32 bytes
char * iniVector = "AAAAAAAA"; // 8 bytes
gcryError = gcry_cipher_open(
&gcryCipherHd, // gcry_cipher_hd_t *
GCRY_CIPHER_SALSA20, // int
GCRY_CIPHER_MODE_STREAM, // int
0); // unsigned int
if (gcryError)
{
printf("gcry_cipher_open failed: %s/%sn",
gcry_strsource(gcryError),
gcry_strerror(gcryError));
return;
}
printf("gcry_cipher_open workedn");
gcryError = gcry_cipher_setkey(gcryCipherHd, salsaKey, 32);
if (gcryError)
{
printf("gcry_cipher_setkey failed: %s/%sn",
gcry_strsource(gcryError),
gcry_strerror(gcryError));
return;
}
printf("gcry_cipher_setkey workedn");
gcryError = gcry_cipher_setiv(gcryCipherHd, iniVector, 8);
if (gcryError)
{
printf("gcry_cipher_setiv failed: %s/%sn",
gcry_strsource(gcryError),
gcry_strerror(gcryError));
return;
}
printf("gcry_cipher_setiv workedn");
size_t txtLength = 101;
char * encBuffer = malloc(txtLength);
char * textBuffer = malloc(txtLength);
memset(textBuffer, 0, 101);
gcryError = gcry_cipher_encrypt(
gcryCipherHd, // gcry_cipher_hd_t
encBuffer, // void *
txtLength, // size_t
textBuffer, // const void *
txtLength); // size_t
if (gcryError)
{
printf("gcry_cipher_decrypt failed: %s/%sn",
gcry_strsource(gcryError),
gcry_strerror(gcryError));
return;
}
printf("gcry_cipher_decrypt workedn");
printf("encBuffer = ");
for (index = 0; index<txtLength-1; index++)
printf("%02X", (unsigned char)encBuffer[index]);
printf("n");
return 0;
}
我使用malloc创建了以下函数(因为您的代码使用malloc)。
char *buffer2hex(char *encBuffer, int txtLength){
char *encHexText = (char *)malloc(txtLength*2+1),
*eht = encHexText;
for (int i = 0; i < txtLength; i++){
int c = (unsigned char)encBuffer[i];
#define tohex(n) ((n)>9?(n)-10+'A':(n)+'0')
*eht++ = tohex(c>>4);
*eht++ = tohex(c&0xf);
#undef tohex
}
*eht = ' ';
return encHexText;
}
在方法的末尾,你可以这样调用它:
char *hex = buffer2hex(encBuffer, txtLength);
printf("%sn", hex); // Use it
free(hex); // and free it!
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 访问类成员而不复制此变量或互斥变量
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 复制文件流C++静态变量
- 为什么我可以使用 memcpy 将一个对象变量复制到另一个对象变量
- 使变量不可复制的紧凑方法
- C++为具有引用成员变量的类创建复制构造函数
- 如何将几个变量复制到其他变量
- 如何在 cuda 中将结构的指针变量从主机复制到设备
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- 复制一个对象并使两者共享一个成员变量 (C++)
- 我的 c 字符串复制函数正在损坏其他变量的堆栈
- 在 C++ 中通过字符串指针复制字符串变量中的字符串
- 将数组中的任意位复制到变量中?
- 如何在 C++ 中复制变量
- 在不复制变量的情况下列出一个变量
- 尝试在类的构造函数中复制变量时出错
- 在c++中如何复制变量而不需要读取/写入权限
- 如何在Visual Studio中复制变量地址