c# - 加密字符串以匹配原始字符串的长度

标签 c# string encryption

我需要一个简单的 C# 算法,该算法将获取一个包含 x 个字符的字符串并将其“加密”为另一个也包含 x 个字符的字符串。它不一定是安全的,但不应该通过简单地查看加密字符串来重建原始字符串。例如,如果我输入“hello”,我应该得到类似“x=w3​​q”的信息。它不应该简单地将每个角色映射到其他东西,但它不必比这复杂得多。它需要对称,所以我需要能够从“x=w3​​q”构建“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/

相关文章:

c# - mono mcs 'Winforms Hello World' 给出编译错误 CS006 : Metadata file 'cscompmgd.dll' could not be found

c# - Linq 的性能包含

c# - Petapoco tt 文件错误

将特殊字符 * 重新插入字符串中的预定义位置

c++ - 将 char* 与字符串宏进行比较

python - 字符串预处理

sql-server - 将 VARBINARY 的字符串表示形式转换为 VARBINARY 值

加密 - PKCS5/7 填充竞争条件?

javascript - 如何在Outlook.com Web邮件中拦截具有Firefox XUL扩展名的电子邮件附件的上传

c# - 如果链接文本包含 html,如何在 ASP .NET MVC Razor View 引擎中使用 @Html.ActionLink() 生成链接,也应该呈现?