[英]Size problem while decoding ciphered text in C
[編輯]
這是密文需要解碼的:
bURCUE}__V|UBBQVT
我的解碼器可以成功獲取密文,但可以將其轉換為某個點。 其余的編碼消息是亂碼。 我檢查了緩沖區和char指針的大小,它們似乎都正確,但找不到缺陷
我希望看到的消息:
SecretLongMessage
屏幕上的解密消息如下所示:
SecretLong | drs`fe
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUZZ_SIZE 1024
char* encryptDecrypt(const char* toEncrypt, int length)
{
char key[] = "1011011011";
char* output = malloc(length + 1);
output[length] = '\0'; //buffer
for (int i = 0; i < length; i++)
{
output[i] = toEncrypt[i] ^ key[i % (sizeof(key)/sizeof(char))];
}
return output;
}
int main(int argc, char* argv[])
{
char buff[BUZZ_SIZE];
FILE *f;
f = fopen("C:\\Users\\Dell\\source\\repos\\XOR\\XOR\\bin\\Debug\\cipher.txt", "r"); // read mode
fgets(buff, BUZZ_SIZE, f);
printf("Ciphered text: %s, size = %d\n", buff,sizeof(buff));
fclose(f);
char* sourceString = buff;
//Decrypt
size_t size = strlen(sourceString);
char* decrypted = encryptDecrypt(buff, size);
//printf("\nsize = %d\n",size);
printf("\nDecrypted is: ");
printf(decrypted);
// Free the allocated buffers
return 0;
}
這是我的提供密碼的C#代碼
String szEncryptionKey = "1011011011";
public Form1()
{
InitializeComponent();
}
string EncryptOrDecrypt(string text, string key)
{
var result = new StringBuilder();
for (int c = 0; c < text.Length; c++)
{
// take next character from string
char character = text[c];
// cast to a uint
uint charCode = (uint)character;
// figure out which character to take from the key
int keyPosition = c % key.Length; // use modulo to "wrap round"
// take the key character
char keyChar = key[keyPosition];
// cast it to a uint also
uint keyCode = (uint)keyChar;
// perform XOR on the two character codes
uint combinedCode = charCode ^ keyCode;
// cast back to a char
char combinedChar = (char)combinedCode;
// add to the result
result.Append(combinedChar);
}
return result.ToString();
}
private void Button1_Click(object sender, EventArgs e)
{
String str = textBox1.Text;
var cipher = EncryptOrDecrypt(str, szEncryptionKey);
System.IO.File.WriteAllText(@"C:\\Users\\Dell\\source\\repos\\XOR\\XOR\\bin\\Debug\\cipher.txt", cipher);
}
您想使用所有字符
char key[] = "1011011011";
用於加密。 但是,數組key
包含一個終止符'\\0'
,當您使用時,它會包含在計算中
key[i % (sizeof(key)/sizeof(char))]
因為sizeof(key)
包含終止符'\\0'
。
您可以使用strlen
來計算字符串長度,也可以使用key[i % (sizeof(key)/sizeof(char))-1]
或將數組初始化為
char key[] = {'1', '0', '1', '1', '0', '1', '1', '0', '1', '1' };
省略終止的'\\0'
。 在后一種情況下,您可以像原始代碼一樣使用sizeof
計算鍵索引
在將C#代碼添加到問題后,很明顯加密在密鑰中不包含'\\0'
。 key.Length
與C中的strlen(key)
相當,而不是sizeof(key)
。
BTW:變量名稱String szEncryptionKey = "1011011011";
C#中的字符串令人誤解,因為它不是C中的零終止字符串。
注意:在您的情況下, strlen(key)
與sizeof(key)-1
相同,因為您沒有指定數組大小並將數組初始化為字符串。 在其他情況下可能會有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.