views:

249

answers:

1

I am encrypting My data in PHP like this :

$encrypted_string = mcrypt_encrypt(MCRYPT_DES, 'abcdefgh' , $input, MCRYPT_MODE_CBC, 'qwerasdf' );
$encrypted_string = base64_encode($encrypted_string);
return  $encrypted_string;

And Decrypting the Same in C# like this :

public string Decrypt(string input)
{
    input = Server.UrlDecode(input);
    byte[] binary = Convert.FromBase64String(input);
    input = Encoding.GetEncoding(28591).GetString(binary);

    DES tripleDes = DES.Create();
    tripleDes.IV = Encoding.ASCII.GetBytes("NAVEEDNA");
    tripleDes.Key = Encoding.ASCII.GetBytes("abcdegef");
    tripleDes.Mode = CipherMode.CBC;
    tripleDes.Padding = PaddingMode.Zeros;

    ICryptoTransform crypto = tripleDes.CreateDecryptor();
    byte[] decodedInput = Decoder(input);
    byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length);
    return Encoding.ASCII.GetString(decryptedBytes);
}

public byte[] Decoder(string input)
{
    byte[] bytes = new byte[input.Length / 2];
    int targetPosition = 0;

    for (int sourcePosition = 0; sourcePosition < input.Length; sourcePosition += 2)
    {
        string hexCode = input.Substring(sourcePosition, 2);
        bytes[targetPosition++] = Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);
    }
    return bytes;
}

When I am trying to decrypt the string in C# it is throwing following exception :

Input string was not in a correct format.

At the Following Line : Byte.Parse(hexCode, NumberStyles.AllowHexSpecifier);

Any idea how to What wrong I am doing ?

+1  A: 

Try Byte.Parse(hexCode, System.Globalization.NumberStyles.HexNumber);

Since AllowHexSpecifier is for 0x1b style hex numbers.

Sam