将字符串加密和解密为固定长度

本文关键字:解密 字符串 加密 | 更新日期: 2023-09-27 18:33:34

我看了很多例子,并尝试了几篇文章。但是他们都没有解决我的问题。

我想加密数据库中的主要列值(整数值(并将其显示在 URL 中。我希望我的 URL 简单易读,所以我不想要冗长的加密值。大多数情况下,我正在寻找大约 5 到 7 个字符的长度。

这可能吗?如果是这样,最好的方法是什么?

加密和解密字符串

http://www.codeproject.com/Tips/306620/Encryption-Decryption-Function-in-Net-using-MD-Cry

将字符串加密和解密为固定长度

根据您的要求,您的整数将不超过 6 个字符 (999999(,编码最多应为 7 个字符,因此 24 位的 XOR 就可以了:

请注意,这种方法可以通过蛮力攻击逆转,但会隐藏大多数凡人的真实数字。

首先我们使用一个三字节键(值只是示例,取你最喜欢的:

byte[] theKey = new byte[]{ 34, 56, 98 }; 

然后对整数进行编码,我们取前三个字节(第四个字节不是必需的,因为您的 INT 不会使用它,只有 20 位最多可以存储 1M,因此最接近的字节数是三个(,我们 XOR 每个字节在键处都有相应的字节:

int cyphered = ((theValue & 0xff) ^ theKey[0]) | 
               ((((theValue >> 8) & 0xff) ^ theKey[1]) << 8) | 
               ((((theValue >> 16) & 0xff) ^ theKey[2]) << 16);

最后,为了使URL是同质的,你把它转换成一个字符串,并用零填充它:

string finalValue = cyphered.ToString().PadLeft(7, '0');

要反转该值,只需使用键再次 XOR 它:

int cyphered = int.Parse(theStringYouReceived);
int decyphered = ((cyphered & 0xff) ^ theKey[0]) | 
                 ((((cyphered >> 8) & 0xff) ^ theKey[1]) << 8)| 
                 ((((cyphered >> 16) & 0xff) ^ theKey[2]) << 16);

正如我所说,它不是AES256安全密码(:D(,但至少会隐藏好奇的数字。

编辑:这是测试用例,它按预期工作:

            byte[] theKey = new byte[] { 34, 56, 98 }; 
            int theValue = 1413;
            int cyphered = ((theValue & 0xff) ^ theKey[0]) |
           ((((theValue >> 8) & 0xff) ^ theKey[1]) << 8) |
           ((((theValue >> 16) & 0xff) ^ theKey[2]) << 16);
            string finalValue = cyphered.ToString().PadLeft(7, '0');
            int scyphered = int.Parse(finalValue);
            int decyphered = ((scyphered & 0xff) ^ theKey[0]) |
                             ((((scyphered >> 8) & 0xff) ^ theKey[1]) << 8) |
                             ((((scyphered >> 16) & 0xff) ^ theKey[2]) << 16);

您当然可以自己滚动,但根据提供的信息,以下库看起来可能很有用。

http://hashids.org/net/

显然,请考虑您的安全要求以及这是否足以满足这些要求。