0

I am trying to figure out how to decrypt the download token created in the following post https://stackoverflow.com/a/4324115/487892

public static string GetDownloadToken(int fileId)
{
    byte[] idbytes = BitConverter.GetBytes(fileId); // 4 bytes 
    byte[] dateTimeBytes = BitConverter.GetBytes(DateTime.Now.ToBinary()); // 8 bytes
    byte[] buffer = new byte[16]; // minimum for an encryption block 
    string password = "password";

    byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
    Array.Copy(idbytes, 0, buffer, 0, idbytes.Length);
    Array.Copy(dateTimeBytes, 0, buffer, idbytes.Length, dateTimeBytes.Length);
    byte[] encryptedBuffer = new byte[256]; 
    using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
    {
        int count = sha1.TransformBlock(buffer, 0, buffer.Length, encryptedBuffer, 0);
        return Convert.ToBase64String(encryptedBuffer, 0, count);
    }
}

My main interest is how do I get the date back so that I can compare it against the current date so that I can expire the token after a period of time? Isn't this doing a 1 way hash?

Community
  • 1
  • 1
drescherjm
  • 10,365
  • 5
  • 44
  • 64

1 Answers1

4

The "encryption" here is not really encryption, it is "hashing". With encryption you can encrypt (make the data unreadable) and decrypt (make it readable again).

With hashing the process is not reversible, i.e. you can't retrieve the original data from the value computed by the hash function,in this case sha1.TransformBlock(..).

If you really want to encrypt with the ability to decrypt you need to use a different mechanism - i.e. not a hashing function.

Here is a pretty detailed SO link that gives more info: Fundamental difference between Hashing and Encryption algorithms

To me your options seem to be:

  1. Use an encryption algorithm instead of a hashing algorithm
  2. Change the method to return an object type that contains the "encryptedBuffer" as the date/time object as members
Community
  • 1
  • 1
imberda
  • 56
  • 3
  • Thanks. That is what I thought was going on. I just wanted to be sure that my understanding of the example was correct. Since the comment said decryption was possible. – drescherjm Sep 19 '12 at 19:09