views:

304

answers:

2

I want my application to encrypt a user password, and at one time password will be decrypted to be sent to the server for authentication. A friend advise me to use HMAC. I wrote the following code in C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] key = encoding.GetBytes("secret");
HMACSHA256 myhmacsha256 = new HMACSHA256(key);
byte[] hashValue = myhmacsha256.ComputeHash(encoding.GetBytes("text"));
string resultSTR = Convert.ToBase64String(hashValue);
myhmacsha256.Clear();

How to decode the password (resultSTR, in this case)?

Thanks.

+3  A: 

An HMAC (Hashed Message Authentication Code) is not encryption, it's hash function (in this case SHA-256) plus some secret key. It's lossy, there is no way to derive the plaintext from the HMAC.

If you want to encrypt some secret data, you should consider using the ProtectedData class instead. More infom including sample code at http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx

Michael Howard-MSFT
How do you send ProtectedData to a server?
dtb
Assuming the computers are in the same domain, you can simply send the blob returned by ProtectedData and have the same account decrypt the blob. it's all seamless :)one of the design goals of the Data Protection API (DPAPI) in Windows, is to have a blob sit naked on the Internet and still be protected. :)
Michael Howard-MSFT
A: 

If there is no way to derive the plaintext from the HMAC. Then Why we use it?

S Jahan
Not everything within the realm of cryptography deals with taking an opaque blob of bytes and retrieving plaintext from them. HMAC is used to give us assurance that data has not been tampered with. See http://en.wikipedia.org/wiki/HMAC
Damien_The_Unbeliever