0

Is it possible to decrypt a string, which was encrypted using PHP, in C#? Here's the code I'm using to encrypt it in PHP:

$string = "Hello. This is a test string.";

$key = "testPassword";
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));

Just need to decrypt that using C# if possible.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Joey Morani
  • 25,431
  • 32
  • 84
  • 131
  • possible duplicate of [Rijndael 256 Encrypt/decrypt between c# and php?](http://stackoverflow.com/questions/3431950/rijndael-256-encrypt-decrypt-between-c-sharp-and-php) – Shai Mar 07 '12 at 11:39
  • Wish you kids would stop nesting all these encryption/hash methods like this. Just use something like `mcrypt` to encrypt the password using a common site password (high entropy, complicated if you want good security). An md5 of the key can NOT be as secure as a good key in the first place. – deed02392 Mar 07 '12 at 11:41
  • This encryption method was taken from this question: http://stackoverflow.com/questions/1289061/best-way-to-use-php-to-encrypt-and-decrypt With 97 up votes it seemed to be the best way. – Joey Morani Mar 07 '12 at 15:13

2 Answers2

1

The decryption part is answered here.

C#

    public static string EncryptString(string message, string KeyString, string IVString)
    {
        byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
        byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);

        string encrypted = null;
        RijndaelManaged rj = new RijndaelManaged();
        rj.Key = Key;
        rj.IV = IV;
        rj.Mode = CipherMode.CBC;

        try
        {
            MemoryStream ms = new MemoryStream();

            using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(message);
                    sw.Close();
                }
                cs.Close();
            }
            byte[] encoded = ms.ToArray();
            encrypted = Convert.ToBase64String(encoded);

            ms.Close();
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: {0}", e.Message);
        }
        finally
        {
            rj.Clear();
        }

        return encrypted;
    }

Decoding base64:

/// <summary>
/// The method create a Base64 encoded string from a normal string.
/// </summary>
/// <param name="toEncode">The String containing the characters to encode.</param>
/// <returns>The Base64 encoded string.</returns>
public static string EncodeTo64(string toEncode)
{

    byte[] toEncodeAsBytes

          = System.Text.Encoding.Unicode.GetBytes(toEncode);

    string returnValue

          = System.Convert.ToBase64String(toEncodeAsBytes);

    return returnValue;

}




/// <summary>
/// The method to Decode your Base64 strings.
/// </summary>
/// <param name="encodedData">The String containing the characters to decode.</param>
/// <returns>A String containing the results of decoding the specified sequence of bytes.</returns>
public static string DecodeFrom64(string encodedData)
{

    byte[] encodedDataAsBytes

        = System.Convert.FromBase64String(encodedData);

    string returnValue =

       System.Text.Encoding.Unicode.GetString(encodedDataAsBytes);

    return returnValue;

}
Community
  • 1
  • 1
Robert Schmidt
  • 699
  • 4
  • 14
  • Please include some code - especially the code that is not on stackoverflow - in your answer. Nobody can know if the link remains active in the future. – ThiefMaster Mar 07 '12 at 11:40
0

C#
First, you need to include using System.Security.Cryptography.

public String AES_encrypt(String Input)
{
    var aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Padding = PaddingMode.PKCS7;
    aes.Key = Convert.FromBase64String("yourkey");//your key
    aes.IV = Convert.FromBase64String("youriv");//your iv
    var encrypt = aes.CreateEncryptor(aes.Key, aes.IV);
    byte[] xBuff = null;
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
        {
            byte[] xXml = Encoding.UTF8.GetBytes(Input);
            cs.Write(xXml, 0, xXml.Length);
        }
        xBuff = ms.ToArray();
    }
    String Output = Convert.ToBase64String(xBuff);
    return Output;
}

public String AES_decrypt(String Input)
{
    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Mode = CipherMode.CBC;
    aes.Padding = PaddingMode.PKCS7;
    aes.Key = Convert.FromBase64String("yourkey");//your key
    aes.IV = Convert.FromBase64String("youriv");//your iv
    var decrypt = aes.CreateDecryptor();
    byte[] xBuff = null;
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, decrypt, CryptoStreamMode.Write))
        {
            byte[] xXml = Convert.FromBase64String(Input);
            cs.Write(xXml, 0, xXml.Length);
        }
        xBuff = ms.ToArray();
    }
    String Output = Encoding.UTF8.GetString(xBuff);
    return Output;
}


PHP

function addpadding($string,$blocksize=32)
{
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad),$pad);
    return $string;
}

function encrypt($string = "")
{
    $key = base64_decode("yourkey");//your key
    $iv = base64_decode("youriv");//your iv
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, addpadding($string), MCRYPT_MODE_CBC, $iv));
}

function strippadding($string)
{
    $slast = ord(substr($string, -1));
    $slastc = chr($slast);
    $pcheck = substr($string, -$slast);
    if(preg_match("/$slastc{".$slast."}/", $string)){
    $string = substr($string, 0, strlen($string)-$slast);
        return $string;
    } else {
        return false;
    }
}
function decrypt($string)
{
    $key = base64_decode("your key");//your key
    $iv = base64_decode("your iv");//
    $string = base64_decode($string);
    return strippadding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $string, MCRYPT_MODE_CBC, $iv));
}
Oliver
  • 43
  • 1
  • 7