且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-22 23:58:32

根据您的要求,您的整数将不超过6个字符(999999),编码应最多7个字符,所以24位的异或将会执行:

As per you requirements, your integers will have no more than 6 chars (999999) and the encoding should be max 7 chars, so a XOR of 24 bits will do it:

请注意,这种方法可以通过暴力攻击来消除,但会隐藏大多数的实数

Beware this method is esily reversible by a bruteforce attack, but will hide the real numbers for the majority of the mortals.

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

First we use a three byte key (the values are just examples, take the ones you like the most:

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

然后进行编码我们采用前三个字节的整数(第四个字节不是必需的,因为您的INT不会使用它,只有20位可以存储高达1M,因此最近的字节计数为3),并且我们的XOR每个都具有相关的字节关键:

Then to encode the integer we take the first three bytes (the fourth byte is not necessary as your INT will not use it, only 20 bits can store up to 1M, so the nearest byte count are three) and we XOR each one with the correpsonding byte at the key:

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

最后,为了使URL相同,您将其转换为字符串并用零填充: / p>

And finally, to make the URL's homogeneous you convert it to an string and pad it with zeroes:

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

要反转该值,请再次使用键:

To reverse the value just XOR it again with the key:

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),但至少会隐藏来自好奇的数字。

As I say, it's not precissely an AES256 security cipher (:D) but at least will hide the numbers from the curious.

编辑:这是测试用例,它的工作原理如下:

here is the test case, it works as expected:

            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);