0

I need to hash a string according to the sha1 algorithm, with the user's secret key, something like: hash = hash (string, secret_key).

I use this code:

byte[] data = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));

But I can not find how to use the secret key in this algorithm.

5
  • 5
    What are you trying to achieve with this? From the little info you posted here it would seem that something like encryption would work better; where the user secret is the secret used to encrypt the data. Commented Jun 26, 2019 at 7:53
  • 1
    I agree with @Tachyon, the use-case described seems quite uncommon. Commented Jun 26, 2019 at 8:07
  • I think OP is on to something, there is a technique called salted hashing which augments the original text with a string so that brute force attacks can't use rainbow tables of pre-computed hashes. Salted hashing simply involves concatenating the input with a "salt" string Commented Jun 26, 2019 at 8:17
  • I just have this task and I am not going to use it. The task contains an example in PHP:hash_hmac('sha1', $input, $secret) Commented Jun 26, 2019 at 8:24
  • If it is just for salting, you can just append the secret key to the input. Commented Jun 26, 2019 at 8:25

1 Answer 1

2

The hash is the result of applying a hash function to data. It maps arbitrary data to fixed size value. This does not require any kind of secret.

The cryptographic process which uses hashes and secret keys is signing data. You may want to create a hash of your data and a MAC (message authentication code) based on public/private key cryptography using the private key.

A hash tells you only that data was modified or not.

A MAC uses any kind of secret, thus it protects also against manipulation. Generally, MACs only work when the sender and receiver know each other.

You could do something like:

public string SignData(string message, string secret)
{
    var encoding = new System.Text.UTF8Encoding();
    var keyBytes = encoding.GetBytes(secret);
    var messageBytes = encoding.GetBytes(message);
    using (var hmacsha1 = new HMACSHA1(keyBytes))
    {
        var hashMessage = hmacsha1.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashMessage);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

How would one retreive the original data from this signed data with the known secret?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.