I am working on an API which requires a header for API authentication. The header contains a hash string which is created using md5 algorithm and a secret key. I want to write a function like this:
public string CreateMD5Hash(string input, string secretKey)
{
return output;
}
I tried to use bouncy castle API. But I couldn't find proper documentation. That is why I couldn't make it use.
CodePudding user response:
Okay BASICALLY let's break this into two simple concepts Cryptography
and Hashing
.
Cryptography
There are three fields secrete key
a value
and an encrypted value
, and two methods.
Encrypt(value, secret-key)
this method getsvalue
andsecret key
and returns theencrypted value
.Decrypt(encrypted-value, secret-key)
and this method getsencrypted value
andsecret key
and returns thevalue
.
likeAES
,DES
, etc ...
Hashing
There are just two fields value
and hashed value
, and one method.
Hash(value)
this method gets thevalue
and returns thehashed value
.
like MD5
, SHA
family, etc ...
Simple right!
So your question is not correct because MD5
is a hashing algorithm that usually is used for hashing passwords and comparing the hash of them.
Now I recommend taking a look at the API you are talking about for authentication.
You can share the link of documentation or an already encrypted header (if it is not sensitive data) to help you.
Update
According to the link, it is using HMAC
with MD5
.
This is the sample in the document, written in PHP
.
$hash = hash_hmac('md5', $string, $key);
You can use this code for C#:
using System.Security.Cryptography;
using System.Text;
...
public string HashHmacMD5(string message, string secret)
{
Encoding encoding = Encoding.UTF8;
using (HMACMD5 hmac = new HMACMD5(encoding.GetBytes(secret)))
{
var msg = encoding.GetBytes(message);
var hash = hmac.ComputeHash(msg);
return BitConverter.ToString(hash).ToLower().Replace("-", string.Empty);
}
}
CodePudding user response:
Your question is somewhat confusing.
For simple API authentication, you want to generate a secret that you want to share with the caller. This secret should be validated on your side.
Normally you would generate a random secure string with length about 50 - this is the secret. You share this secret with the caller - normally you warn the caller to securely store the value, since there is no way to recover it. Do not store this secret in the database.
You would generate a salt and hash the secret. You store both the salt and the hashed secret in the database. When the request comes in, you extract the value in the header, hash it with the salt and compare the result with the hashed secret in the database. User would be authenticated if they are match.
Is this more inline with your thinking? Is your question, how to hash it properly?