15

I have a string encrypted in PHP that I would like to decrypt in C#. I used the tutorial below to do the encryption, but am having problems decrypting. Can anyone post an example on how to do this?

http://www.sanity-free.org/131/triple_des_between_php_and_csharp.html

1
  • 1
    DES as an algorithm does not have anything to do with PHP, C# or any other specific language. Your question, as I understand it, boils down to that you perhaps have a bug in your C# code, and want someone to write correct code for your behalf. Commented Oct 22, 2008 at 4:52

2 Answers 2

14

Hope this helps:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Decrypt("47794945c0230c3d"));
    }

    static string Decrypt(string input)
    {
        TripleDES tripleDes = TripleDES.Create();
        tripleDes.IV = Encoding.ASCII.GetBytes("password");
        tripleDes.Key = Encoding.ASCII.GetBytes("passwordDR0wSS@P6660juht");
        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);
    }

    static 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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Use Envonding.UTF8 rather than Encoding.ASCII , if you want to encrypt special charachters corretcly
13

If you are not tied to tripleDES, but just need to pass encrypted data between php and .net, this will work for you. It's in VB and C# below.

BEGIN PHP CODE

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

// I blantantly stole, tweaked and happily used this code from: 
// Lord of Ports http://www.experts-exchange.com/M_1736399.html

$ky = 'lkirwf897+22#bbtrm8814z5qq=498j5'; // 32 * 8 = 256 bit key
$iv = '741952hheeyy66#cs!9hjv887mxx7@8y'; // 32 * 8 = 256 bit iv

$text = "Here is my data to encrypt!!!";

$from_vb = "QBlgcQ2+v3wd8RLjhtu07ZBd8aQWjPMfTc/73TPzlyA=";   // enter value from vb.net app here to test

$etext = encryptRJ256($ky, $iv, $text);
$dtext = decryptRJ256($ky, $iv, $etext);
$vtext = decryptRJ256($ky, $iv, $from_vb);

echo "<HR>orignal string: $text";
echo "<HR>encrypted in php: $etext";
echo "<HR>decrypted in php: $dtext";
echo "<HR>encrypted in vb: $from_vb";
echo "<HR>from vb decrypted in php: $vtext"; 
echo "<HR>If you like it say thanks! richard dot varno at gmail dot com";

exit;


function decryptRJ256($key,$iv,$string_to_decrypt)
{
    $string_to_decrypt = base64_decode($string_to_decrypt);
    $rtn = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_decrypt, MCRYPT_MODE_CBC, $iv);
    $rtn = rtrim($rtn, "\0\4");
    return($rtn);
}

function encryptRJ256($key,$iv,$string_to_encrypt)
{
    $rtn = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $string_to_encrypt, MCRYPT_MODE_CBC, $iv);
    $rtn = base64_encode($rtn);
    return($rtn);
}    
?>

BEGIN VB.NET CODE (console app)

Imports System
Imports System.Text
Imports System.Security.Cryptography
Imports System.IO

Module Module1

    ' I blantantly stole, tweaked and happily used this code from: 
    ' Lord of Ports http://www.experts-exchange.com/M_1736399.html

    Sub Main()

        'Shared 256 bit Key and IV here
        Dim sKy As String = "lkirwf897+22#bbtrm8814z5qq=498j5"  '32 chr shared ascii string (32 * 8 = 256 bit)
        Dim sIV As String = "741952hheeyy66#cs!9hjv887mxx7@8y"  '32 chr shared ascii string (32 * 8 = 256 bit)

        Dim sTextVal As String = "Here is my data to encrypt!!!"

        Dim eText As String
        Dim dText As String

        eText = EncryptRJ256(sKy, sIV, sTextVal)
        dText = DecryptRJ256(sKy, sIV, eText)

        Console.WriteLine("key: " & sKy)
        Console.WriteLine()
        Console.WriteLine(" iv: " & sIV)
        Console.WriteLine("txt: " & sTextVal)
        Console.WriteLine("encrypted: " & eText)
        Console.WriteLine("decrypted: " & dText)
        Console.WriteLine("If you like it say thanks! richard dot varno at gmail dot com")
        Console.WriteLine("press any key to exit")
        Console.ReadKey(True)

    End Sub

    Public Function DecryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_decrypt As String)

        Dim sEncryptedString As String = prm_text_to_decrypt

        Dim myRijndael As New RijndaelManaged
        myRijndael.Padding = PaddingMode.Zeros
        myRijndael.Mode = CipherMode.CBC
        myRijndael.KeySize = 256
        myRijndael.BlockSize = 256

        Dim key() As Byte
        Dim IV() As Byte

        key = System.Text.Encoding.ASCII.GetBytes(prm_key)
        IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)

        Dim decryptor As ICryptoTransform = myRijndael.CreateDecryptor(key, IV)

        Dim sEncrypted As Byte() = Convert.FromBase64String(sEncryptedString)

        Dim fromEncrypt() As Byte = New Byte(sEncrypted.Length) {}

        Dim msDecrypt As New MemoryStream(sEncrypted)
        Dim csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)

        csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length)

        Return (System.Text.Encoding.ASCII.GetString(fromEncrypt))

    End Function


    Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String)

        Dim sToEncrypt As String = prm_text_to_encrypt

        Dim myRijndael As New RijndaelManaged
        myRijndael.Padding = PaddingMode.Zeros
        myRijndael.Mode = CipherMode.CBC
        myRijndael.KeySize = 256
        myRijndael.BlockSize = 256

        Dim encrypted() As Byte
        Dim toEncrypt() As Byte
        Dim key() As Byte
        Dim IV() As Byte

        key = System.Text.Encoding.ASCII.GetBytes(prm_key)
        IV = System.Text.Encoding.ASCII.GetBytes(prm_iv)

        Dim encryptor As ICryptoTransform = myRijndael.CreateEncryptor(key, IV)

        Dim msEncrypt As New MemoryStream()
        Dim csEncrypt As New CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)

        toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt)

        csEncrypt.Write(toEncrypt, 0, toEncrypt.Length)
        csEncrypt.FlushFinalBlock()

        encrypted = msEncrypt.ToArray()

        Return (Convert.ToBase64String(encrypted))

    End Function

End Module

BEGIN C# ALTERNATIVE (console app)

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

class Program {
  static void Main(string[] args) {

    //Shared 256 bit Key and IV here
    const string sKy = "lkirwf897+22#bbtrm8814z5qq=498j5"; //32 chr shared ascii string (32 * 8 = 256 bit)
    const string sIV = "741952hheeyy66#cs!9hjv887mxx7@8y"; //32 chr shared ascii string (32 * 8 = 256 bit)

    var sTextVal = "Here is my data to encrypt!!!";

    var eText = EncryptRJ256(sKy, sIV, sTextVal);
    var dText = DecryptRJ256(sKy, sIV, eText);

    Console.WriteLine("key: " + sKy);
    Console.WriteLine();
    Console.WriteLine(" iv: " + sIV);
    Console.WriteLine("txt: " + sTextVal);
    Console.WriteLine("encrypted: " + eText);
    Console.WriteLine("decrypted: " + dText);
    Console.WriteLine("press any key to exit");
    Console.ReadKey(true);
  }

  public static string DecryptRJ256(string prm_key, string prm_iv, string prm_text_to_decrypt) {

    var sEncryptedString = prm_text_to_decrypt;

    var myRijndael = new RijndaelManaged() {
      Padding = PaddingMode.Zeros,
      Mode = CipherMode.CBC,
      KeySize = 256,
      BlockSize = 256
    };

    var key = Encoding.ASCII.GetBytes(prm_key);
    var IV = Encoding.ASCII.GetBytes(prm_iv);

    var decryptor = myRijndael.CreateDecryptor(key, IV);

    var sEncrypted = Convert.FromBase64String(sEncryptedString);

    var fromEncrypt = new byte[sEncrypted.Length];

    var msDecrypt = new MemoryStream(sEncrypted);
    var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

    csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

    return (Encoding.ASCII.GetString(fromEncrypt));
  }

  public static string EncryptRJ256(string prm_key, string prm_iv, string prm_text_to_encrypt) {

    var sToEncrypt = prm_text_to_encrypt;

    var myRijndael = new RijndaelManaged() {
      Padding = PaddingMode.Zeros,
      Mode = CipherMode.CBC,
      KeySize = 256,
      BlockSize = 256
    };

    var key = Encoding.ASCII.GetBytes(prm_key);
    var IV = Encoding.ASCII.GetBytes(prm_iv);

    var encryptor = myRijndael.CreateEncryptor(key, IV);

    var msEncrypt = new MemoryStream();
    var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

    var toEncrypt = Encoding.ASCII.GetBytes(sToEncrypt);

    csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
    csEncrypt.FlushFinalBlock();

    var encrypted = msEncrypt.ToArray();

    return (Convert.ToBase64String(encrypted));
  }

}

3 Comments

Hi, I used the text "Hitesh" and Test the C# code on LINQPad and the decrypted text is "Hitesh□□□□□□□□□□□□□□□□□□□□□□□□□□" any Idea ? here is the screenshot. oi62.tinypic.com/1113v43.jpg
I have to change the c# code to: var encoding = new UTF8Encoding(); var key = encoding.GetBytes(prm_key); var IV = encoding.GetBytes(prm_iv); I couldn't find a way to generate the appropriated “prm_iv” using Convert.FromBase64String(prm_iv), then I tried Encoding.ASCII.GetBytes and I could generate the key but couldn’t have the right result from PHP. So I stumbled in to another question/ansewer under the same context I tried the GetBytes from UTF8Encoding and finally worked. Thanks to everyone.
The php side worked at once! Best code snippet so far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.