Cha*_*tra 5 c# asp.net encryption cryptography
我研究了很多例子并尝试了几篇文章。但他们都没有解决我的问题。
我想加密数据库中的主列值(整数值)并将其显示在 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 };
Run Code Online (Sandbox Code Playgroud)
然后,为了对整数进行编码,我们取前三个字节(第四个字节不是必需的,因为你的 INT 不会使用它,只有 20 位可以存储最多 1M,所以最接近的字节数是 3),我们将每个字节与键对应的字节:
int cyphered = ((theValue & 0xff) ^ theKey[0]) |
((((theValue >> 8) & 0xff) ^ theKey[1]) << 8) |
((((theValue >> 16) & 0xff) ^ theKey[2]) << 16);
Run Code Online (Sandbox Code Playgroud)
最后,为了使 URL 具有同质性,您可以将其转换为字符串并用零填充:
string finalValue = cyphered.ToString().PadLeft(7, '0');
Run Code Online (Sandbox Code Playgroud)
要反转该值,只需与密钥再次进行异或:
int cyphered = int.Parse(theStringYouReceived);
int decyphered = ((cyphered & 0xff) ^ theKey[0]) |
((((cyphered >> 8) & 0xff) ^ theKey[1]) << 8)|
((((cyphered >> 16) & 0xff) ^ theKey[2]) << 16);
Run Code Online (Sandbox Code Playgroud)
正如我所说,它并不完全是 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5929 次 |
| 最近记录: |