How to Encrypt a String in .Net and Decrypt it Using mcrypt_encrypt in PHP

No.of Views1397
Bookmarked0 times
Downloads 
Votes0
By  nsoonhui   On  10 May 2010 02:05:05
Tag : CSharp , Cryptography
How to Encrypt a String in .Net and Decrypt it Using mcrypt_encrypt in PHP
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Sometimes you have to encrypt a string using .Net library, and decrypt it back in PHP, or vice versa, or across other languages. I have a webservice which is written in PHP and a .Net program that calls the webservice. In the exchange I would have to encrypt a string at .Net's end and decrypt it in PHP end.

The encryption and decryption in .Net is pretty straightforward; all you have to use is the Cryptography  library in .Net.  Examples are abound on Internet, so you don't have to crack your head to find a working solution and modify them to suit your needs. Similarly, it's easy if you want to do encryption and decryption in PHP.

But to get encryption and decryption thing to work on different languages can be a bit tricky. I have spent quite a lot of time to make things to work. So here I am now posting my code, and hope that it will help other people.

Encryption in .Net. In this example I take a string, and convert it into encrypted hexadecimal string.

private static string CreateEncryptedString(string myString, string hexiv, string key)
        {
            RijndaelManaged alg = new RijndaelManaged();
            alg.Padding = PaddingMode.Zeros;
            alg.Mode = CipherMode.CBC;
            alg.BlockSize = 16 * 8;
            alg.Key = ASCIIEncoding.UTF8.GetBytes(key);
            alg.IV = StringToByteArray(hexiv);
            ICryptoTransform encryptor = alg.CreateEncryptor(alg.Key, alg.IV);

            MemoryStream msStream = new MemoryStream();
            CryptoStream mCSWriter = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write);
            StreamWriter mSWriter = new StreamWriter(mCSWriter);
            mSWriter.Write(myString);
            mSWriter.Flush();
            mCSWriter.FlushFinalBlock();

            var EncryptedByte = new byte[msStream.Length];
            msStream.Position = 0;
            msStream.Read(EncryptedByte, 0, (int)msStream.Length);

            return ByteArrayToHexString(EncryptedByte);
          
        }
        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;
        }
        public static string ByteArrayToHexString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

 

There is one thing to note. The key size must be 16. Which means that key parameter must be a string with 16 characters. Or else the encryption won't work and will throw a System.Security.Cryptography.CryptographicException : Specified key is not a valid size for this algorithm exception. Also note that the hexiv must be a hexadecimal string with 32 characters, meaning that every character inside the hexiv must be hexadecimal (0-9, a-f).

$cipher_alg = MCRYPT_RIJNDAEL_128;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, 
$encrypted_string , MCRYPT_MODE_CBC, trim(hex2bin(trim($hexiv))));

 

Where $encrypted_string is the encrypted string returned by the above function, and the hexiv is the same as the hexiv in the .Net code.

Conclusion

In this article , i have shared with you how we can do encrption and decryption in .NET and PHP combination. i hope this is help much more to you all.

 
Sign Up to vote for this article
 
About Author
 
nsoonhui
Occupation-Not Provided
Company-Not Provided
Member Type-Fresh
Location-Malaysia
Joined date-06 May 2010
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top