我需要一个简单的 C# 算法,该算法将获取一个包含 x 个字符的字符串并将其“加密”为另一个也包含 x 个字符的字符串。它不一定是安全的,但不应该通过简单地查看加密字符串来重建原始字符串。例如,如果我输入“hello”,我应该得到类似“x=w3q”的信息。它不应该简单地将每个角色映射到其他东西,但它不必比这复杂得多。它需要对称,所以我需要能够从“x=w3q”构建“hello”。
到目前为止,我已经尝试过 RijndaelManaged 和 RSA 加密,但加密后的字符串比原始字符串长很多。
有什么想法吗?
最佳答案
您可以开始使用 ROT13 算法,然后根据前一个字符更改偏移量。
例子:“你好”
'h' 的 ROT13 --> 'u'
因为 U 是字母表中的第 21 个字母,接下来您将使用 ROT21:
'e' 的 ROT8 --> 'z'
等等。
这不仅可以保持长度不变,还可以处理额外的字符,只要您将它们添加到字母表中即可。
如果目前还不够清楚,我深表歉意,我正在打电话。
编辑:
这是一些代码,这会更有意义:
static String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String originalString)
{
String returnString = "";
int shift = alphabet.Length / 2;
foreach (char c in originalString)
{
int nextIndex = alphabet.IndexOf(c) + shift;
if (nextIndex > alphabet.Length)
nextIndex = nextIndex - alphabet.Length;
returnString += alphabet[nextIndex];
shift = alphabet.IndexOf(alphabet[nextIndex]);
}
return returnString;
}
public static String decrypt(String encryptedString)
{
String returnString = "";
int shift = alphabet.Length / 2;
foreach (char c in encryptedString)
{
int nextIndex = alphabet.IndexOf(c) - shift;
if (nextIndex < 0)
nextIndex = alphabet.Length + nextIndex; // nextIndex is negative so we are decreasing regardless
returnString += alphabet[nextIndex];
shift = alphabet.IndexOf(c);
}
return returnString;
}
字母表可以随心所欲地扩展。它不安全,但它很简单,不能仅仅通过查看就可以轻易破译。
关于c# - 加密字符串以匹配原始字符串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730973/