MD5

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

Encode a string using an MD5 algorithm. The algorithm can be found on the wiki.


Contents

[edit] C#

using System.Text;
using System.Security.Cryptography;
 
/// <summary>
/// Provides static helper methods for calculation of MD5 hashes of strings
/// byte array objects.  This class does not implement any specific exception
/// handling therefore all exceptions are thrown out to the caller
/// </summary>
public sealed class MD5Helpers
{
  /// <summary>
  /// Prevents initialisation of new instances of the <see cref="MD5Helpers"/> class.
  /// Constructor is not required or should be accessible as all class methods are static.
  /// </summary>
  private MD5Helpers() {}
 
  /// <summary>
  /// Calculates the MD5 hash of the given byte array
  /// </summary>
  /// <param name="inputData">The byte array value to create the hash for.</param>
  /// <param name="removeDashes">If set to <c>true</c> dashes are removed from the returned hash.</param>
  /// <returns>String representation of the calculated MD5 hash.</returns>
  public static string GetMD5Hash(byte[] inputData, bool removeDashes)
  {
    byte[] md5Buffer = GetMD5Hash(inputData);
    string md5Hash = BitConverter.ToString(md5Buffer);
 
    if (removeDashes)
    {
      md5Hash = md5Hash.Replace("-", string.Empty);
    }
 
    return md5Hash;
  }
 
  /// <summary>
  /// Calculates the MD5 hash of the given byte array
  /// </summary>
  /// <param name="inputData">Byte array to calculate the hash for.</param>
  /// <returns>Byte array representation of the calculated hash.</returns>
  public static byte[] GetMD5Hash(byte[] inputData)
  {
    MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
    byte[] md5Buffer = md5Provider.ComputeHash(inputData);
 
    return md5Buffer;
  }
 
  /// <summary>
  /// Calculates the MD5 hash of the given string.
  /// </summary>
  /// <param name="inputData">The input data (assumes ASCII encoding)</param>
  /// <param name="removeDashes">If set to <c>true</c> dashes are removed from the returned hash.</param>
  /// <returns>String representation of the calculated MD5 hash.</returns>
  public static string GetMD5Hash(string inputData, bool removeDashes)
  {
    byte[] inputBuffer = ASCIIEncoding.ASCII.GetBytes(inputData);
 
    return GetMD5Hash(inputBuffer, removeDashes);
  }
}

[edit] D

Library: Tango

module md5test ;
import tango.io.digest.Md5 ;
import tango.io.Stdout ;
void main(char[][] args) {
  auto md5 = new Md5() ;
  for(int i = 1 ; i < args.length ; i++){
    md5.update(args[i]) ;
    Stdout.formatln("[{}]=>\n[{}]", args[i], md5.hexDigest()) ;
  }
}

Sample output:

>md5test "The quick brown fox jumped over the lazy dog's back"
[The quick brown fox jumped over the lazy dog's back]=>
[e38ca1d920c4b8b8d3946b2c72f01680]

[edit] Java

Modified from mindprod's Java Glossary:

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
/**
 * Test MD5 digest computation
 *
 * @author Roedy Green
 * @version 1.0
 * @since 2004-06-07
 */
public final class MD5{
	public static void main(String[] args) throws UnsupportedEncodingException,
			NoSuchAlgorithmException{
		byte[] theTextToDigestAsBytes=
				"The quick brown fox jumped over the lazy dog's back"
						.getBytes("8859_1");
		MessageDigest md= MessageDigest.getInstance("MD5");
		md.update(theTextToDigestAsBytes);
		byte[] digest= md.digest();
 
		// dump out the hash
		for(byte b: digest){
			System.out.printf("%02X", b & 0xff);
		}
		System.out.println();
	}
}

[edit] OCaml

# Digest.to_hex(Digest.string "The quick brown fox jumped over the lazy dog's back") ;;
- : string = "e38ca1d920c4b8b8d3946b2c72f01680"

[edit] Perl

Library: Digest::MD5

use Digest::MD5 qw(md5_hex);
 
print md5_hex("The quick brown fox jumped over the lazy dog's back"), "\n";

[edit] The same in OO manner

use Digest::MD5;
 
$md5 = Digest::MD5->new;
$md5->add("The quick brown fox jumped over the lazy dog's back");
print $md5->hexdigest, "\n";

[edit] PHP

$string = "The quick brown fox jumped over the lazy dog's back";
echo md5( $string );

[edit] Python

Using builtin libraries:

>>> import md5
>>> print md5.md5("The quick brown fox jumped over the lazy dog's back").hexdigest()
e38ca1d920c4b8b8d3946b2c72f01680

[edit] SQL

Works with: MySQL


SELECT MD5('The quick brown fox jumped over the lazy dog\'s back')

[edit] UNIX Shell

UNIX Shells are typically scripting languages, so they execute system commands. (Such as md5, in this case.)

echo "The quick brown fox jumped over the lazy dog's back"|md5
Personal tools