Vernam Cipher XOR并不总是有效 [英] Vernam Cipher XOR not always working
本文介绍了Vernam Cipher XOR并不总是有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我创建的加密方法,
Here's the encryption method I create,
public string Encrypt(string Text, string Key)
{
string newText = Text;
string newKey = Key;
string newResult = string.Empty;
//EQUATE TEXT AND KEY LENGTH
if (Text.Length > Key.Length)
{
int left = 0;
for (int i = 0; i < Math.Abs(Text.Length - Key.Length); i++)
{
newKey += Key.Substring(left, 1);
left += 1;
if (left == Key.Length) { left = 0; }
}
}
else if (Text.Length < Key.Length)
{
newKey = Key.Substring(0, Text.Length);
}
//GET ASCII CODE > CONVERT TO BINARY > MERGE BINARY
for (int i = 0; i < Text.Length; i++)
{
byte txtASC = Encoding.Default.GetBytes(newText)[i];
byte keyASC = Encoding.Default.GetBytes(newKey)[i];
string txtBIN = Convert.ToString(Convert.ToInt32(txtASC), 2);
string keyBIN = Convert.ToString(Convert.ToInt32(keyASC), 2);
string newBIN = string.Empty;
newBIN = Convert.ToString(Convert.ToInt32(txtBIN, 2) + Convert.ToInt32(keyBIN, 2), 2); //CHANGE + TO - IN DECRYPT METHOD
newResult += ((char)Convert.ToInt32(newBIN, 2)).ToString();
}
return newResult;
}
当我使用简单的'a'密钥和单个'apple'字样时,加密和解密工作。
但是当我输出句子和更长的密钥时,我再也看不到解密的结果了。
有人可以解释我的代码中有什么问题吗?
When I use a simple 'a' key, and a single 'apple' word, both encrypt and decrypt works.
But when I put sentences and a longer key, I can't read the result of decryption anymore.
Can someone explain what's wrong in my code?
推荐答案
你想要一个清单吗?
很难发现你抱怨的问题 - 你的代码不能用字符串 Apple和1234的关键所以你的测试有点怀疑......对于Vernam Cipher,我希望得到一个与输入字符串长度相同的加密字符串,而你的代码不会这样做。它也没有实现Vernam Cipher:缺少XOR有一点线索。
http://www.cryptomuseum.com/crypto/vernam.htm [ ^ ]
我认为你需要坐下来,阅读链接,然后重新开始。
顺便说一句:你不需要创建一个足够长的新密钥来覆盖整个消息:
只需创建一个从零开始的索引,并检查它的长度关键:
Would you like a list?
It's hard to spot the problem you are complaining of - your code doesn't work with a string "Apple" and a key of "1234" so your testing is a little suspect...For a Vernam Cipher, I would expect to get an encrypted string the same length as the input string, and your code doesn't do that. It also doesn't implement a Vernam Cipher: the lack of an XOR in there is a bit of a clue.
http://www.cryptomuseum.com/crypto/vernam.htm[^]
I think you need to sit down, read the link, and start all over again.
BTW: You don't need to create a new key that is long enough to cover the whole message:
Just create an index starting at zero, and check it against the length of the key:
int keyIndex = 0;
foreach (char c in Text)
{
if (keyIndex >= key.Length) keyIndex = 0;
char keyValue = key[keyIndex];
...
keyIndex++;
}
这篇关于Vernam Cipher XOR并不总是有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文