Generating a unique *and* random URL in C#

前端 未结 5 787
孤街浪徒
孤街浪徒 2021-02-08 04:44

My ultimate goal is to create a URL that is unique and cannot be guessed/predicted. The purpose of this URL is to allow users to perform operations like verifying their email ad

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-08 05:15

    You can generate 128 bit, "random," unique numbers by running a counter through an AES counter keyed with a random key. As long as the same key is used this will never repeat any output.

    static byte[] AESCounter(byte[] key, ulong counter) {
        byte[] InputBlock = new byte[16];
        InputBlock[0] = (byte)(counter & 0xffL);
        InputBlock[1] = (byte)((counter & 0xff00L) >> 8);
        InputBlock[2] = (byte)((counter & 0xff0000L) >> 16);
        InputBlock[3] = (byte)((counter & 0xff000000L) >> 24);
        InputBlock[4] = (byte)((counter & 0xff00000000L) >> 32);
        InputBlock[5] = (byte)((counter & 0xff0000000000L) >> 40);
        InputBlock[6] = (byte)((counter & 0xff000000000000L) >> 48);
        InputBlock[7] = (byte)((counter & 0xff00000000000000L) >> 54);
        using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
        {
            AES.Key = key;
            AES.Mode = CipherMode.ECB;
            AES.Padding = PaddingMode.None;
            using (ICryptoTransform Encryptor = AES.CreateEncryptor())
            {
                return Encryptor.TransformFinalBlock(InputBlock, 0, 16);
            }
        }
    }
    

提交回复
热议问题