PHP Classes
elePHPant
Icontem

Decrypt C# Encryption String with PHP is this possible?: I want to Decrypt the C# Encryption string in php

Recommend this page to a friend!
  All requests RSS feed  >  Decrypt C# Encryption String with PHP...  >  Request new recommendation  >  A request is featured when there is no good recommended package on the site when it is posted. Featured requests  >  No recommendations No recommendations  

Decrypt C# Encryption String with PHP is this possible?

A request is featured when there is no good recommended package on the site when it is posted. Edit

by muabshir - 2 years ago (2016-10-21)

I want to Decrypt the C# Encryption string in php

This request is clear and relevant.
This request is not clear or is not relevant.

+3

Encryption String: F7EBC908B106D4282FA705D0EED915DBE002774B1A152DCC Key: ABC12345 __________________________________

C# Code _________________________________

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
 
namespace THK.PAMS_DataAccess.DataAccess
{
   
    public class EncryptionHelper : Dictionary<string, string>
    {
        // Change the following keys to ensure uniqueness
        // Must be 8 bytes
        protected byte[] _keyBytes = { 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18 };
 
        // Must be at least 8 characters
        protected string _keyString = "ABC12345";
 
        // Name for checksum value (unlikely to be used as arguments by user)
        protected string _checksumKey = "__$$";
 
        /// <summary>
        /// Creates an empty dictionary
        /// </summary>
        public EncryptionHelper()
        {
        }
 
        /// <summary>
        /// Creates a dictionary from the given, encrypted string
        /// </summary>
        /// <param name="encryptedData"></param>
        public EncryptionHelper(string encryptedData)
        {
            // Descrypt string
            string data = Decrypt(encryptedData);
 
            // Parse out key/value pairs and add to dictionary
            string checksum = null;
            string[] args = data.Split('&');
 
            foreach (string arg in args)
            {
                int i = arg.IndexOf('=');
                if (i != -1)
                {
                    string key = arg.Substring(0, i);
                    string value = arg.Substring(i + 1);
                    if (key == _checksumKey)
                        checksum = value;
                    else
                        base.Add(HttpUtility.UrlDecode(key), HttpUtility.UrlDecode(value));
                }
            }
 
            // Clear contents if valid checksum not found
            if (checksum == null || checksum != ComputeChecksum())
                base.Clear();
        }
 
        /// <summary>
        /// Returns an encrypted string that contains the current dictionary
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            // Build query string from current contents
            StringBuilder content = new StringBuilder();
 
            foreach (string key in base.Keys)
            {
                if (content.Length > 0)
                    content.Append('&');
                content.AppendFormat("{0}={1}", HttpUtility.UrlEncode(key),
                  HttpUtility.UrlEncode(base[key]));
            }
 
            // Add checksum
            if (content.Length > 0)
                content.Append('&');
            content.AppendFormat("{0}={1}", _checksumKey, ComputeChecksum());
 
            return Encrypt(content.ToString());
        }
 
        /// <summary>
        /// Returns a simple checksum for all keys and values in the collection
        /// </summary>
        /// <returns></returns>
        protected string ComputeChecksum()
        {
            int checksum = 0;
 
            foreach (KeyValuePair<string, string> pair in this)
            {
                checksum += pair.Key.Sum(c => c - '0');
                checksum += pair.Value.Sum(c => c - '0');
            }
 
            return checksum.ToString("X");
        }
 
        /// <summary>
        /// Encrypts the given text
        /// </summary>
        /// <param name="text">Text to be encrypted</param>
        /// <returns></returns>
        protected string Encrypt(string text)
        {
            try
            {
                byte[] keyData = Encoding.UTF8.GetBytes(_keyString.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] textData = Encoding.UTF8.GetBytes(text);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms,
                  des.CreateEncryptor(keyData, _keyBytes), CryptoStreamMode.Write);
                cs.Write(textData, 0, textData.Length);
                cs.FlushFinalBlock();
                return GetString(ms.ToArray());
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
 
        /// <summary>
        /// Decrypts the given encrypted text
        /// </summary>
        /// <param name="text">Text to be decrypted</param>
        /// <returns></returns>
        protected string Decrypt(string text)
        {
            try
            {
                byte[] keyData = Encoding.UTF8.GetBytes(_keyString.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] textData = GetBytes(text);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms,
                  des.CreateDecryptor(keyData, _keyBytes), CryptoStreamMode.Write);
                cs.Write(textData, 0, textData.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception)
            {
                return String.Empty;
            }
        }
 
        /// <summary>
        /// Converts a byte array to a string of hex characters
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected string GetString(byte[] data)
        {
            StringBuilder results = new StringBuilder();
 
            foreach (byte b in data)
                results.Append(b.ToString("X2"));
 
            return results.ToString();
        }
 
        /// <summary>
        /// Converts a string of hex characters to a byte array
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected byte[] GetBytes(string data)
        {
            // GetString() encodes the hex-numbers with two digits
            byte[] results = new byte[data.Length / 2];
 
            for (int i = 0; i < data.Length; i += 2)
                results[i / 2] = Convert.ToByte(data.Substring(i, 2), 16);
 
            return results;
        }
    }
}
  • 1 Clarification request
  • 1. by Michael Cummings - 2 years ago (2016-10-25) Reply

    Just to let you know I created a class to do this after see something on tweeter. I'll try to get it up on Github and on PhpClasses as well for you in the next couple days.

    • 2. by muabshir - 2 years ago (2016-10-25) in reply to comment 1 by Michael Cummings Comment

      i really love to see your work if you got success ur a super coder for me waiting for you work :)

    • 3. by muabshir - 2 years ago (2016-10-28) in reply to comment 1 by Michael Cummings Comment

      can you email me the solution with example

      mubashir7 at gmail.com

Ask clarification

1 Recommendation

Encryption Helper: Encrypt and decrypt of GET query lists

This recommendation solves the problem.
This recommendation does not solve the problem.

+3

by Michael Cummings package author package author Reputation 60 - 2 years ago (2016-10-28) Comment

It's awaiting approval now but you can access it on GitHub

github.com/Dragonrun1/encryption-helper

or through Packagist

packagist.org/packages/dragonrun1/encryption-helper

Sorry took longer then I expected to get it up some where you could access it but ended up getting a bit more polish in the mean time while I continue to work on it as I had time.

  • 4 Comments
  • 1. by muabshir - 2 years ago (2016-10-31) Reply

    Thanks for the replay can you please tell me which PHP version you are using because i am getting following errors while running example. php file

    Warning: Unsupported declare 'strict_types' in C:\xampp\htdocs\encryption-helper-master\example.php on line 2

    Warning: Unsupported declare 'strict_types' in C:\xampp\htdocs\encryption-helper-master\src\EncryptionHelper.php on line 2

    Fatal error: Default value for parameters with a class type hint can only be NULL in C:\xampp\htdocs\encryption-helper-master\src\EncryptionHelper.php on line 64

  • 2. by muabshir - 2 years ago (2016-10-31) Reply

    You are the best i have just download PHP7 in my computer and everything is working as per my requirement thanks sir you are supper coder thanks

  • 3. by muabshir - 2 years ago (2016-10-31) Reply

    Michael can we encrypt data with this code or only decrypt if encryption is possible can you guide me how

  • 4. by Michael Cummings package author package author - 2 years ago (2016-11-03) in reply to comment 3 by muabshir Reply

    I exposed both the encrypt() and decrypt() methods which you can use directly plus you can use addQuery() and deleteQuery() to change the query list then use the class in any string content just like the original c# to have it generate a complete query string because of the magic method __toString(). Just as the example.php says looking at the example in the specs/ directory should show you all the features include stuff that wasn't available or not direct visible in the original code but I thought could be useful.


Recommend package
: 
: