开发者

C#'s opposite to PHP's bin2hex() [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

Convert hex string to byte array

I am encrypting a string in PHP and I would like to decrypt this string using C#. The last line of the encryption function will return a hexadecimal representation of the encrypted string. Unfortunately for me, though, I cannot figure out how to reverse this conversion through C#. I will post my source below:

PHP:

echo encrypt('hello'); // Returns '60eb44e27e73ba1d'
function encrypt($string) {
        //Key
        $key = "12345678";

        //Encryption
        $cipher_alg = MCRYPT_TRIPLEDES;

        $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,MCRYPT_MODE_ECB), MCRYPT_RAND); 

        $encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_ECB, $iv);开发者_开发知识库
        return bin2hex($encrypted_string);
    }

The only issue I am having is the hex2bin conversion in C# - the rest of the decryption function I have working. Feel free to ask for any further details.

Hopefully there is some simple solution out there that I don't know about. I appreciate any responses.

Regards,

Evan


use

string hexstr = "60eb44e27e73ba1d";

byte[] R  = (from i in Enumerable.Range(0, hexstr.Length / 2) select Convert.ToByte(hexstr.Substring(i * 2, 2), 16)).ToArray();

MSDN references:

  • http://msdn.microsoft.com/en-us/library/aka44szs.aspx
  • http://msdn.microsoft.com/en-us/library/c7xhf79k.aspx
  • http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx
  • http://msdn.microsoft.com/en-us/library/bb397926.aspx


I found a simple solution online ... don't know how this just came to me:

 public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }

This is the reverse to PHP's bin2hex function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜