我写了一个自定义加密的代码。这是一个挑战。现在,由于一些原因,它无法工作,比如:
Encrypt("abc","hello everyone")返回: sdfhsjfjs Decrypt("abc","sdfhsjfjs") Retruns: diuifidu
public int CountCharInStringAccordingToArray(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count - 1;
}
public int CountCharInString(string Text)
{
int Count = 0;
foreach (char x in Text)
{
Count++;
}
return Count;
}
public string Encrypt(string Key, string PlainText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(PlainText)];
int[] EncryptedInt = new int[CountCharInString(PlainText)];
char[] EncryptedChar = new char[CountCharInString(PlainText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
TempText[i] = (int)PlainText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(PlainText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
EncryptedInt[i] = TempKey[Index] + TempText[i];
Index++;
EncryptedChar[i] = (char)EncryptedInt[i];
}
return new string(EncryptedChar);
}
public string Decrypt(string Key, string EncryptedText)
{
int[] TempKey = new int[CountCharInString(Key)];
int[] TempText = new int[CountCharInString(EncryptedText)];
int[] DecryptedInt = new int[CountCharInString(EncryptedText)];
char[] DecryptedChar = new char[CountCharInString(EncryptedText)];
for (int i = 0; i < CountCharInStringAccordingToArray(Key); i++)
{
TempKey[i] = (int)Key[i];
}
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
TempText[i] = (int)EncryptedText[i];
}
int Index = 0;
for (int i = 0; i < CountCharInStringAccordingToArray(EncryptedText); i++)
{
if (Index == CountCharInStringAccordingToArray(Key))
{
Index = 0;
}
DecryptedInt[i] = TempText[i] - TempKey[Index];
Index++;
DecryptedChar[i] = (char)DecryptedInt[i];
}
return new string(DecryptedChar);
}我也知道字符串有一个长度属性,只是我忘了改正它。
发布于 2013-03-28 11:53:22
更改线路
return Count - 1;在CountCharInStringAccordingToArray中
return Count;代码的表示形式:
String That(String key, String text, int sign) {
return new String(Enumerable.Range(0, text.Length).Select((x, i) => (char)(text.ToArray()[i]+sign*key.ToArray()[i%key.Length])).ToArray());
}
public String Encrypt(String key, String text) {
return That(key, text, 1);
}
public String Decrypt(String key, String text) {
return That(key, text, -1);
}它的工作原理很简单。请看图表:

重复使用key中的字符将其添加到text中,并生成一个被认为是加密的序列。解密只是通过减法进行的反向操作。
一个字节中可以存储的最大值是0x0ff,但可见字符的最大值是0x7e,即~和0x7e+0x7e=0xfc。
因此,只要你的密钥和文本在可见字符的范围内,它就不会导致溢出。也就是说,您可以将加密后的序列正确解密为原始序列。
发布于 2013-03-28 11:11:35
Get string length and output string
使用系统;
class MainClass {
public static void Main() {
string str1 = "ABCDEabcde1234567890";
Console.WriteLine("str1: " + str1);
Console.WriteLine("Length of str1: " + str1.Length);
}
}https://stackoverflow.com/questions/15673568
复制相似问题