0

I have records in database that are plain text. From outside source I get md5 hash of string value.

Entities DB = ...
DB.SomeObjects.FirstOrDefault(p => p.PlainTextValue == md5HashedValue);

How can I convert this PlainTextValue to md5?

SpoksST
  • 776
  • 1
  • 8
  • 24

1 Answers1

0

That's an awful implementation. To use it, you need to read all the rows from the DB, calculate its MD5 on the application side, and compare them with the provided value. That happens every time you execute this query. This is because the DB hasn't a way to do that calculation, and thus, the query cannot be converted into a SQL query. (In case it's not clear enough: you can only read all the texts from the DB, store them in a List or somewhere, and then, in the applicaiton side, calculate all of the hashes... every time)

The ideal solution would be to have the MD5 calculated on the DB, on a new column, or on a related table, to avoid repeating the calculations, and having to read and transfer all the texts to the application. (Then, whenever the text changes or a new text is inserted, calculate the hash, and store it in the DB).

To calculate an MD5 using C# you can look this SO Q&A.

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • Optimization and performance cosniderations aside, the answer is yes, and you should update this accepted 'answer' to actually include the C# MD5 snippet in the context of EF (or a Linq to Entity) statement, instead of simply referencing another SO answer.. – Brett Caswell Apr 15 '15 at 13:35
  • @BrettCaswell I'm sorry to disagree, but 1) The answer to "How can I convert this PlainTextValue to md5?" can't be "yes", or am I missing some question? 2) You cannot do an MD5 calculation on a L2E query: it cannot be converted to SQL, and thus it will fail, throwing an exception. You must materialize the query and get out of the L2E domain to be able to compute the hash. 3) You should know that "simply referencing a SO question" is a good idea because the answer is self-contained in SO. It's only necessary to copy information when you link to external sources which could dissapear. – JotaBe Apr 15 '15 at 17:17
  • 4) And finally, I usually use the cite "Premature optimization is the root of all evil". But, in this instance, repeating such an expensive operation as and MD5 hash calculation is simply crazy. I usually don't simply the asked question, but also add some related advice that, believe it or not, can get really useful, and make the OP open his eyes. – JotaBe Apr 15 '15 at 17:19