Calculate a Md5 Hash from a String

Calculate a MD5 hash from a string

As per MSDN

Create MD5:

public static string CreateMD5(string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = md5.ComputeHash(inputBytes);

return Convert.ToHexString(hashBytes); // .NET 5 +

// Convert the byte array to hexadecimal string prior to .NET 5
// StringBuilder sb = new System.Text.StringBuilder();
// for (int i = 0; i < hashBytes.Length; i++)
// {
// sb.Append(hashBytes[i].ToString("X2"));
// }
// return sb.ToString();
}
}

MD5 Hash From String

Need to get MD5 hash from string.

Then first you need to convert your string to binary data in some form. How you do that will depend on your requirements, but it'll probably be Encoding.GetBytes for some encoding... you need to work out which encoding though. Does this hash need to match the hash created somewhere else, for example?

Get an error MD5 is null.

That's because you're using MD5.Create incorrectly. The argument is an algorithm name. You should almost certainly just use the parameterless overload instead.

I suspect you want something like:

byte[] hash;
using (MD5 md5 = MD5.Create())
{
hash = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
}
// Now convert the binary hash into text if you must...

Calculate the MD5 hash of the string

$schoolName.$certId.$barcode.$indate does not have . chars in the output - that's the concatenate operator. That input gives a string of:

大连民族学院图书馆2012081507011874222013-03-20

which when hashed, gives:

a6019b5589029bf9378cfff4c631fc7d

The substring 3,8 of which is:

19b55890

Also note that MD5 is not encryption, it's a one way hash of the input string. It's also considered fairly insecure now; it's recommended to use SHA-256 based hashes if you're able to switch.

Scala one-liner to generate MD5 Hash from string

It's just a analogue to this java code but without StringBuilder (it's up to you)

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
String password = "secret";
messageDigest.update(password.getBytes());
byte[] bytes = messageDigest.digest();
StringBuilder stringBuilder = new StringBuilder();
for (byte aByte : bytes) {
stringBuilder.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
System.out.println(stringBuilder.toString());

Let's consider second line:

md.digest(inputStr.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft("") {_ + _}
  1. md.digest(inputStr.getBytes()) ---- take bytes from String
  2. md.digest(inputStr.getBytes()).map(0xFF & _) --- bitwise & with every item of array (map return a new array)
  3. md.digest(inputStr.getBytes()).map(0xFF & ).map { "%02x".format() } map with formatting each item.
  4. md.digest(inputStr.getBytes()).map(0xFF & ).map { "%02x".format() }.foldLeft("") {_ + _} it's typical fold, in our case starting from left and init value "", (if it will be easier for you, it's "far" analogue of StringBuilder behaving in above example). I recommend you to read about fold, reduce and etc. actions in scala. e.g. https://coderwall.com/p/4l73-a/scala-fold-foldleft-and-foldright

Calculate MD5 of a string in C++

You are passing a final newline to the md5sum program, but not to your code.

You can see that the bash <<< operator adds a newline:

$ od -ta <<<Hello
0000000 H e l l o nl
0000006

To avoid this, use printf:

$ printf '%s' Hello | od -ta
0000000 H e l l o
0000005
$ printf '%s' Hello | md5sum
8b1a9953c4611296a827abf8c47804d7 -

Alternatively, you could include a newline in your program version:

std::string str("Hello\n");

Calculate MD5 in C - Display output as string

You have it right, you just can't use printf("%s", digest); to print digest as a string. Note the unsigned char digest[16]; will be an array of unsigned char and will not be nul-terminated. You cannot print it as a string. Instead print each element as a hexadecimal number with 2 characters, e.g.

for (int i = 0; i < 16; i++)
printf("%02x", digest[i]);
putchar ('\n');

Your complete example would then be:

#include <stdio.h>
#include <string.h>
#include <openssl/md5.h>

void compute_md5(char *str, unsigned char digest[16]);

int main()
{
unsigned char digest[16];
compute_md5("hello world", digest);
for (int i = 0; i < 16; i++)
printf("%02x", digest[i]);
putchar ('\n');
return 0;
}

void compute_md5(char *str, unsigned char digest[16]) {
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, str, strlen(str));
MD5_Final(digest, &ctx);
}

Example Use/Output

$ ./bin/md5openssl
5eb63bbbe01eeed093cb22bb8f5acdc3

Creating A String From digest

If you need to create a string from digest that you can print with printf ("%s\n", buf); then you create a buffer and instead of writing the 2-char hex representation to stdout, use sprintf to write it to a buffer, nul-terminate the buffer and then print the string. You could do:

int main()
{
unsigned char digest[16];
char buf[sizeof digest * 2 + 1];
compute_md5("hello world", digest);
for (int i = 0, j = 0; i < 16; i++, j+=2)
sprintf(buf+j, "%02x", digest[i]);
buf[sizeof digest * 2] = 0;
printf ("%s\n", buf);
return 0;
}

(output is the same)

Let me know if that isn't what you are looking for.

MD5 hashing in a string in C

Probably one of the biggest inconveniences of C is string handling. It's all very low level. char* is not simply a string that can be modified and written to however; it's just a pointer to memory.

There are several ways to correct the code, but here is my recommended fix:

// hashes two words and writes the digest to output.
void hashfunc(char* word1, char* word2, char* output) {
//concat both words
char concat[100];
strcpy(concat, word1);
strcat(concat, word2);

MD5_CTX md5;
MD5_Init(&md5);
MD5_Update(&md5,concat,strlen(concat));
MD5_Final(output,&md5);
}

Changes were:

  • Using a temporary work buffer to join the words together to be hashed.
  • Not returning a value, instead opting to let the user pass a buffer in to handle the return value.

Benefits of the second change is that the consumer can use memory on the stack rather than always being forced to deal with memory allocations inside of the function. (The other method would be to malloc memory and return that, which is slower and must be freed manually).

Also I'm not exactly sure how the MD5 library you're using works, but you can probably avoid the manual concatenation altogether:

void hashfunc(char* word1, char* word2, char* output) {
MD5_CTX md5;
MD5_Init(&md5);
MD5_Update(&md5,word1,strlen(word1));
MD5_Update(&md5,word2,strlen(word2));
MD5_Final(output,&md5);
}

And in case you need a usage example:

char ret[100];
hashfunc(a, b, ret);

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

Computing the MD5 hash of a string in scala

You may be reinventing a very tiny wheel here, but just write a function to do what you want: take a string, use MessageDigest, and return whatever (hex string, byte array) you need.

import java.security.MessageDigest

def md5(s: String) = {
MessageDigest.getInstance("MD5").digest(s.getBytes)
}

md5("Hello")

P.S. I don't write Scala, but this works and it's left as an exercise to the reader to turn it into anything other than an Array[Byte]



Related Topics



Leave a reply



Submit