Replicate C# code hash to PHP - c#

I have to replicate C# hash from the code below into PHP. I have been searching but didn't find a solution so far.
private string createHash(string stringToHash)
{
// Byte[] originalBytes;
MD5 hash = MD5.Create();
hash = new MD5CryptoServiceProvider();
// originalBytes = ASCIIEncoding.Default.GetBytes(stringToHash);
byte[] data = hash.ComputeHash(Encoding.Default.GetBytes(stringToHash));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
Thanx for you help!

PHP has an in-built function - MD5
<?php
$hash = md5("plain text");
echo $hash;
?>

Related

rijndael 128 cfb C# and php

I have a problem. I have a method to encrypt a password in php and in C# but i cannot get the same results with both algorithms. Someone can help me?
PhP
<?php
$password = 'MySecretPass';
$secret = '65rgt85k89xrDAr3';
$iv = 'AAAAAAAAAAAAAAAA';
$td = mcrypt_module_open('rijndael-128', '', 'cfb','');
mcrypt_generic_init($td, $secret, $iv);
$password = mcrypt_generic($td, $password);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
$password=base64_encode($password);
echo $password;
?>
C#
var password = padString("MySecretPass");
txtEncrypt.Text = Convert.ToBase64String(EncryptStringToBytes(password,
Encoding.UTF8.GetBytes("65rgt85k89xrDAr3"),
Encoding.UTF8.GetBytes("AAAAAAAAAAAAAAAA"), PaddingMode.None));
txtEncrypt.Text = txtEncrypt.Text;
static byte[] EncryptStringToBytes(string plainText, byte[] key, byte[] iv, PaddingMode mode)
{
byte[] encrypted;
using (var rijAlg = new RijndaelManaged { Mode = CipherMode.CFB, BlockSize = 128, Padding = mode })
{
rijAlg.Key = key;
rijAlg.IV = iv;
var encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}
return encrypted;
}
private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.Length % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
The results for PhP is "/KNlzi/fZOERWL79", but for c# is /J643dvAR4/Gh0aYHdshNw==. I don't know why my results are different. In addition, I have wrote the code in Java and I get the same result than in C#.
Thanks in advance.
It's probably that Encoding.GetBytes(string) returns "Unicode encoding". That's an encoding that actually does not exist, but it returns UTF-16. On the other hand you treat your key and IV as ASCII characters.
So whichever encoding PHP is using at the time, there will be a mismatch. You should explicitly define which encoding should be used when converting textual strings to bytes, both in the PHP code as in your C# code.

Convert Python Code to C# Code (generate HMAC)

In C#, I have to create the MD5 hmac token based on following python code.
from hashlib import md5
trans_5C = "".join(chr(x ^ 0x5c) for x in xrange(256))
trans_36 = "".join(chr(x ^ 0x36) for x in xrange(256))
blocksize = md5().block_size
def hmac_md5(key, msg):
if len(key) > blocksize:
key = md5(key).digest()
key += chr(0) * (blocksize - len(key))
o_key_pad = key.translate(trans_5C)
i_key_pad = key.translate(trans_36)
return md5(o_key_pad + md5(i_key_pad + msg).digest())
if __name__ == "__main__":
h = hmac_md5("9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1", "1387797294")
print h.hexdigest() # 9036a1a3f654aefeab426e9f7e17288e
As in windowsphone8 we don't have MD5 implementation so i downloaded the MD5 Class from here thanks to jeff. It works generating MD5 but my problem is still here. The above Python code generates the exact required token 9036a1a3f654aefeab426e9f7e17288e, but mine generates 8280c9a3804b53792324b62363fc22fd.
Can anyone translate the python code to c#?
My below c# code is very simple.
string token = string.Empty;
string key = "9T5zhB4sTNGxMJ-iDdO-Ow" + "8rdp7erdig0m6aa72lhanvuk01" + "pizza1";
string message = "1387797294";
Encoding encoding = Encoding.UTF8;
//token 9036a1a3f654aefeab426e9f7e17288e
Debug.WriteLine(MD5.GetMd5String(message + key));
First, in python, you can simply use the hmac module:
>>> import hmac
>>> hmac.new("9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1", "1387797294").hexdigest()
'9036a1a3f654aefeab426e9f7e17288e'
Second, your C# code does not implement the HMAC algorithm, but simply returns a MD5 hash.
The python equivalent would be simply
>>> import md5
>>> md5.new("1387797294" + "9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1").hexdigest()
'8280c9a3804b53792324b62363fc22fd'
You can find an implemention of the HMAC algorithm in C# e.g. at CodePlex.
From the project page:
Project Description
This is a simple implementation of the MD5
cryptographic hashing algorithm and HMAC-MD5. This class consists of
fully transparent C# code, suitable for use in .NET, Silverlight and
WP7 applications.
Also, here's another simple implementation I've come up with:
string key = "9T5zhB4sTNGxMJ-iDdO-Ow" + "8rdp7erdig0m6aa72lhanvuk01" + "pizza1";
string message = "1387797294";
var encoding = Encoding.UTF8;
var md = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
var trans_5C = new byte[64];
var trans_36 = new byte[64];
var b_key = encoding.GetBytes(key);
// TODO: also check if key is to short
if (b_key.Length > 64)
b_key = md.ComputeHash(b_key);
for (int i = 0; i < 64; i++)
{
trans_5C[i] = 92;
trans_36[i] = 54;
if (i < key.Length)
{
trans_5C[i] ^= b_key[i];
trans_36[i] ^= b_key[i];
}
}
byte[] inner = md.ComputeHash(trans_36.Concat(encoding.GetBytes(message)).ToArray());
var hash = md.ComputeHash(trans_5C.Concat(inner).ToArray());
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("x2"));
var result = sb.ToString(); // = 9036a1a3f654aefeab426e9f7e17288e

md5 hash confusion

My company uses the following algorithm to hash passwords before store it in the database:
public static string Hash(string value)
{
byte[] valueBytes = new byte[value.Length * 2];
Encoder encoder = Encoding.Unicode.GetEncoder();
encoder.GetBytes(value.ToCharArray(), 0, value.Length, valueBytes, 0, true);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(valueBytes);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
stringBuilder.Append(hashBytes[i].ToString("x2"));
}
return stringBuilder.ToString();
}
To me it sounds like a trivial md5 hash, but when I tried to match a password (123456) the algorithm gives me ce0bfd15059b68d67688884d7a3d3e8c, and when I use a standard md5 hash it gives me e10adc3949ba59abbe56e057f20f883e.
A iOS version of the site is being build, and the users needs to login, the password will be hashed before sent. I told the iOS team to use a standard md5 hash, but of course it don't worked out.
I can't unhash the password and hash it again using the standard md5 (of course), and I don't know what exactly tell to the iOS team, in order to get the same hash.
Any help?
You need to use the same encoding on both ends (probably UTF8).
If you replace your code with
byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes("123456"));
, you'll get e10adc3949ba59abbe56e057f20f883e.
You need to use UTF8 instead of Unicode. The following code works exactly like the PHP md5() function:
public static string md5(string value)
{
byte[] encoded = ASCIIEncoding.UTF8.GetBytes(value);
MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
byte[] hashCode = md5Provider.ComputeHash(encoded);
string ret = "";
foreach (byte a in hashCode)
ret += String.Format("{0:x2}", a);
return ret;
}

MD5 in Object-C and C#

I have a method written in c# to get md5:
public static string encryptPasswordWithMd5(string password)
{
MD5 md5Hasher = MD5.Create();
byte[] data = md5Hasher.ComputeHash(Encoding.Unicode.GetBytes(password));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
sb.Append(data[i].ToString("x2"));
return sb.ToString();
}
Now I need to implement the same function using objective-c, how to do it?
ps: I have used the way here http://discussions.apple.com/thread.jspa?threadID=1509152&tstart=96
the code in objc is
-(NSString *) encryptPasswordWithMd5: (NSString *) _password
{
const char * cStr = [_password cStringUsingEncoding: NSUTF16LittleEndianStringEncoding];
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(cStr, strlen(cStr), result);
return [NSString stringWithFormat: #"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1],
result[2], result[3],
result[4], result[5],
result[6], result[7],
result[8], result[9],
result[10], result[11],
result[12], result[13],
result[14], result[15]
];
}
but they don't get the same result. take 'admin' as example, c# is "19a2854144b63a8f7617a6f225019b12" but the objc is "0CC175B9C0F1B6A831C399E269772661";
Check this links (last post). It shows how to calculate MD5 hash in Objective-C.
BTW: You can also simplify MD5 computation in C# a bit
public static string encryptPasswordWithMd5(string password)
{
var md5 = new MD5CryptoServiceProvider();
var originalBytes = ASCIIEncoding.Default.GetBytes(password);
var encodedBytes = md5.ComputeHash(originalBytes);
return BitConverter.ToString(encodedBytes);
}

.NET Equivalent of MD5.hex() in Javascript

I'm trying to connect to a website I made with auth that uses MD5.hex(password) to encrypt the password before sending it to the PHP. How could I achieve the same encryption in C#?
EDIT1:
Javascript (YUI Library):
pw = MD5.hex(pw);
this.chap.value = MD5.hex(pw + this.token.value);
C#.NET
string pw = getMD5(getHex(getMD5(getHex(my_password)) + my_token));
Utility:
public string getMD5(string input)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5 md5Hasher = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public string getHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int tmp = c;
hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
return hex;
}
Using .NET's MD5 Class in the System.Security.Cryptography namespace.
The link above contains a short code example; you might also want to check out Jeff Attwood's CodeProject article .NET Encryption Simplified.

Categories

Resources