【问题标题】:How to return this array as string?如何将此数组作为字符串返回?
【发布时间】:2017-05-12 06:54:19
【问题描述】:
    static char* test_encrypt_ecb_verbose(char* plain_text_char, char* key_char)
{
uint8_t i,j, buf[64];
uint8_t plain_text[64];
uint8_t* outstr;
outstr = '\0';
memcpy(key,key_char,16) ;
memcpy(plain_text, plain_text_char, 64);
memset(buf, 0, 64);

printf("ECB encrypt verbose:\n\n");
printf("plain text:\n");
for(i = (uint8_t) 0; i < (uint8_t) 4; ++i)
{
    phex(plain_text + i * (uint8_t) 16);
}
printf("\n");

printf("key:\n");
phex(key);
printf("\n");

// print the resulting cipher as 4 x 16 byte strings
printf("ciphertext:\n");
for(i = 0; i < 4; ++i)
{
    AES128_ECB_encrypt(plain_text + (i*16), key, buf+(i*16));
    phex(buf + (i*16));
//function to encrypt
}
printf("decryptedtext:\n");
for (i = 0; i < 4; ++i)
{
    AES128_ECB_decrypt(buf + (i * 16), key, plain_text + (i * 16));
    phex(plain_text + (i * 16));
//function to decrypt
}
//memcpy(outstr, buf, 64);

for (i = 0; i < 4; i++)
{
    for (j = 0; j < 16; j++)
    {
        outstr[j] = buf + (i * 16);
    }
}

在上面的代码 sn-p 中,我想将加密后的输出数组返回为 string 。我的两个尝试在最后。但那些都不正确。任何人都可以提出正确的方法吗?

【问题讨论】:

  • 不要使用 ECB 模式,它不安全,请参阅ECB mode,向下滚动到企鹅。而是使用带有随机IV的CBC模式,只需在加密数据前加上IV用于解密即可,它不需要保密。
  • 好的。是的,需要注意的一点。下次我会注意的

标签: c arrays string pointers return-value


【解决方案1】:

char 数组和 char 指针不是一回事。

如果您需要更多详细信息,请参考this post

它会为您提供从 char 数组中获取 char * 的解决方案

char* p = &a[0];

a 是您的 char 数组, p 是您的目标指针 然后返回你的指针。使用您的代码,您也可以直接使用您获得的char * 作为函数参数

【讨论】:

    【解决方案2】:

    要取回它,您应该添加一个额外的参数:

    static void test_encrypt_ecb_verbose(char* plain_text_char, char* key_char, char** cipher_text_char)
    {
        ... your function ...
    
        *cipher_text_char = malloc(64);
        memcpy(*cipher_text_char, buf, 64);
    }
    

    来自你刚才做的调用者

    char* cipher_text_char = NULL;
    
    test_encrypt_ecb_verbose(plain_text_char, key_char, &cipher_text_char);
    

    test_encrypt_ecb_verbose 执行后,cipher_text_char 将指向函数内部分配的内存。

    举个例子:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    char* myfunc(char* src, char** dst, int len)
    {
        *dst = (char*)malloc(len);
    
        memcpy(*dst, src, len);
    
        return *dst;
    }
    
    int main(int argc, char* argv[])
    {
        char* src = "MyFuncTest";
        char* dst = NULL;
        char* p = NULL;
    
        p = myfunc(src, &dst, strlen(src) + 1);
    
        printf("dst = %s\n", dst);
        printf("p = %s\n", p);
    
        return 0;
    }
    

    输出是:
    dst = MyFuncTest
    p = MyFuncTest

    【讨论】:

    • 以及如何使用 *cipher_text_char 编写返回语句?
    • 是否应该在定义中添加“return *cipher_text_char;”作为return语句?
    • 它没有打印所需的东西。有什么可以改变的?
    • “所需的东西”是什么意思?您应该得到与上次 printf 相同的结果。不是吗?您是如何更改代码的?
    • 有什么方法可以给你看完整的代码吗?那我可以告诉你好一点。感谢您的及时回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多