字符串末尾的随机字符

时间:2016-10-18 00:07:14

标签: c string gcc

我创建了一个函数来加密C中的字符串(使用GCC),但是我在解密字符串的末尾获得了随机字符。 该函数将保存第一个字符处输入字符串的长度和第二个字符使用的键(第一个字符-1)。所有要加密的字符串都有10到30之间的长度,所以我希望在转换为存储为char时没有问题。

这里的整个代码:

#include <stdio.h> //printf
#include <stdlib.h> //malloc
#include <string.h> //strlen

char* x(const char* toEncrypt);
char* y(const char* toDecrypt);

int main() {
    const char *secret = "hellohello";
    printf("original: %s\n", secret);

    const char* crypted = x(secret);
    printf("crypted: %s\n", crypted);

    const char* decrypted = y(crypted);
    printf("decrypted: %s\n", decrypted);

    return 0;
}

char* x(const char* toEncrypt) {
    printf("x->toEncrypt = %s\n", toEncrypt);

    int offset = 0, i = 0;
    int length = strlen(toEncrypt);
    printf("\tx->length = %d\n", length);

    char key = ((char)(*toEncrypt))-1;
    printf("\tx->key = %c\n", key);

    char* output = (char*)malloc(length+3); //toEncrypt length + (length + key + null)

    output[offset++] = (char)length;
    output[offset++] = key;

    for (i = 0; i < length; i++) {
        printf("i = %d\toffset = %d\tchar = %c\n", i, offset, toEncrypt[i]);
        output[offset++] = toEncrypt[i] ^ key;
    }
    output[offset] = '\0';

    printf("\tx->output = %s\n", output);
    return output;
}

char* y(const char* toDecrypt) {
    printf("y->toDecrypt = %s\n", toDecrypt);

    int offset = 0, i = 0;
    int length = (int)toDecrypt[offset++] ;
    printf("\tx->length = %d\n", length);

    char key = (char)toDecrypt[offset++];
    printf("\ty->key = %c\n", key);

    char* output = (char*)malloc(length+1);

    for (i = 0; i < length; i++) {
        printf("i = %d\toffset = %d\tchar = %c\n", i, offset, (char)toDecrypt[offset] ^key);
        output[i] = toDecrypt[offset++] ^ key;
    }

    output[offset] = '\0';

    printf("\ty->output = %s\n", output);
    return output;
}

输出:

original: hellohello
x->toEncrypt = hellohello
        x->length = 10
        x->key = g
i = 0   offset = 2      char = h
i = 1   offset = 3      char = e
i = 2   offset = 4      char = l
i = 3   offset = 5      char = l
i = 4   offset = 6      char = o
i = 5   offset = 7      char = h
i = 6   offset = 8      char = e
i = 7   offset = 9      char = l
i = 8   offset = 10     char = l
i = 9   offset = 11     char = o
        x->output =
g
crypted:
g
y->toDecrypt =
g
        x->length = 10
        y->key = g
i = 0   offset = 2      char = h
i = 1   offset = 3      char = e
i = 2   offset = 4      char = l
i = 3   offset = 5      char = l
i = 4   offset = 6      char = o
i = 5   offset = 7      char = h
i = 6   offset = 8      char = e
i = 7   offset = 9      char = l
i = 8   offset = 10     char = l
i = 9   offset = 11     char = o
        y->output = hellohellobe
decrypted: hellohellobe

1 个答案:

答案 0 :(得分:6)

我认为问题在于这个语句(在函数y()中 - 函数x()中的相同语句是正常的):

output[offset] = '\0';

应该是:

output[i] = '\0';

改变它应该有用。