2016-11-30 213 views
1

我試圖解決在C++中訓練的簡單任務:異或加密/解密。但我的gamma()函數無法正常工作。它會創建奇怪長度的結果字符串,比原始字符少或超過。我不明白,爲什麼。我試圖將\0添加到結果字符串的末尾,但它不起作用。C++異或加密/解密(異或密碼)不適用於我

gamma()功能

void gamma(char *s1, char *s2, char *res) 
{ 
    for (int i = 0; i < strlen(s1); i++) { 
     res[i] = s1[i]^s2[i]; 
} 

我原來的字符串是 char source[255] = "1234", key[255] = "avsc", result[255];

gamma()創建了一個陌生的字符串length=5。輸出

例子:

source: 1234dfdfsd key: avsc234567 source(hex): 31 32 33 34 64 66 64 66 73 64 key(hex): 61 76 73 63 32 33 34 35 36 37 result (hex): 50 44 40 57 56 55 50 53 45 53 4D - length??? try to restore source: 1234dfdfsdM¶ try to restore source in hex: 31 32 33 34 64 66 64 66 73 64 4D 14

+1

不能在空值終止字符串使用XOR,你需要單獨保留的長度。 –

+0

你期望看到什麼作爲輸出? – SomeWittyUsername

+0

我試過使用C++字符串,但是我看到一些錯誤,比如'52 \t 18 test.cpp \t [錯誤]沒有匹配'operator ^'(操作數類型是'std :: string {aka std :: basic_string }'和'std :: string {aka std :: basic_string }')' @SomeWittyUsername 一串字節,可以解釋爲一串十六進制數字。他們的長度必須匹配原始文本的長度... – WallOfBytes

回答

0

你的函數改爲

void gamma(char *s1, char *s2, char *res) 
{ 
    for (int i = 0; i < strlen(s1); i++) { 
     res[i] = s1[i]^s2[i]; 
    } 
    res[strlen(s1)] = '\0'; 
} 
+0

我試過了,但它不起作用。 – WallOfBytes

+1

'xor'的結果可以是'\ 0',所以它仍然存在問題 – Slava

+0

您如何顯示結果?顯示你的代碼。 – Sniper

1

這不是一個好主意,使用二進制數據char*std::string,因爲很多地方假定持有零終止的字符串。 (爲std::string這是acctually較好,但仍存在一些問題),所以最好使用std::vector<unsigned char>的二進制數據:

typedef std::vector<uin8_t> data; 
data gamma(const std::string &str, const std::string &key) 
{ 
    data r(str.length()); 
    for(size_t i = 0; i < str.length(); ++i) 
     r[i] = str[i]^key[i%key.length()]; 
    return r; 
} 
+0

是的,我認爲,使用字符向量而不是字符串類型是非常好的主意。謝謝! – WallOfBytes