0

I need a C# method to encrypt an integer to a string of five characters where valid characters are a-z, A-Z, 0-9

I need to do this because I am sending URLs to users that look like this...

http://www.website.com.au/3

Users will see data at this URL that is specific to them. The data is not ultra sensitive, but it is seen as unacceptable to view someone else's broadcast simply by entering the next number:

http://www.website.com.au/4

However there is also a need to keep the URL's short and readable as the URLs could reach you via a text message and we don't want to loose text message space by a massively long encrypted value so

http://www.website.com.au/3

Might become

http://www.website.com.au/a6Yqo

I realise this level of encryption is quite weak but it is good enough for these broadcasts

public string Encrypt(int number)
{
}

public int Decrypt(string encrypted)
{
}

Where do I start?

Petras
  • 4,686
  • 14
  • 57
  • 89
  • It is possible to add at least 2 characters to the valid characters? Having 64 instead of 62 characters nicely lets you use base 64. Note that at a maximum, you are currently supporting slightly less than a bilion separate messages. – Maarten Bodewes Mar 30 '14 at 15:38
  • If you can accept 6 characters, you could use a 32 bit blockcipher like skipjack. – CodesInChaos Mar 30 '14 at 16:16
  • I just looked at skip32 at https://github.com/eleven41/Eleven41.Skip32. Not bad as it returns a 9 digit integer as the encrypted value. Would prefer it shorter but I guess its safer and I may be able to live with the 9 digits – Petras Mar 30 '14 at 21:23

2 Answers2

2

Not exactly what you need but will do the job

    public static string Encrypt(int value)
    {
        return Convert.ToBase64String(BitConverter.GetBytes(value)).Replace("==","");
    }

    public static int Decrypt(string value)
    {
        if(value.Length!=6)
            throw new ArgumentException("Invalid length.");

        return BitConverter.ToInt32(Convert.FromBase64String(value + "=="),0);
    }

Results:

0 : AAAAAA

1 : AQAAAA

2 : AgAAAA

3 : AwAAAA

4 : BAAAAA

5 : BQAAAA

6 : BgAAAA

7 : BwAAAA

8 : CAAAAA

9 : CQAAAA

10 : CgAAAA

11 : CwAAAA

12 : DAAAAA

13 : DQAAAA

14 : DgAAAA

15 : DwAAAA

16 : EAAAAA

17 : EQAAAA

18 : EgAAAA

19 : EwAAAA

20 : FAAAAA

21 : FQAAAA

22 : FgAAAA

23 : FwAAAA

24 : GAAAAA
Abdullah Saleem
  • 3,701
  • 1
  • 19
  • 30
  • 1
    Base-64 encoding is *not* encryption. This offers zero security as Base64 is trivial to identify and reverse. – Dai Mar 07 '17 at 06:20
0

Create a table which maps the "hash" to the "resource". The "hash" is the alphanumeric you will send to your users and the "resource" is some kind of identificator (the number in your case) that allows you to locate and serve the proper resource.

When you need to send a new url to some user just generate a random "hash" of required length and use the table to check that it is unique.

Oleg Estekhin
  • 8,063
  • 5
  • 49
  • 52