Red de conocimiento informático - Material del sitio web - Cómo utilizar PHP para implementar cifrado y descifrado DES coherente con C#

Cómo utilizar PHP para implementar cifrado y descifrado DES coherente con C#

Utilice PHP para implementar cifrado y descifrado DES que sea coherente con C#. Puede encontrar muchos en Internet, pero después de realizar pruebas, descubrió que ninguno funciona. El código correcto a continuación es el que encontré después de mucho esfuerzo. Espero que puedas usarlo en la integración del sistema.

Nota: La longitud de la clave es de 8 bits o menos.

[csharp]?view?plain?copy?print?

//¿Versión C# del algoritmo de cifrado/descifrado DES?

¿Usando System;?

Usando System.Data;?

usando?

Usando System.Web;?

¿usando?

¿usando?

usando?System.Web.UI.WebControls;?

usando?System.Web.UI.WebControls.WebParts ;?

usando?System.Web.UI.HtmlControls;?

usando?System.Data.SqlClient;?

usando?

using?

using?

public.class.Des{?

// ¿Claves de cifrado y descifrado?

cadena estática privada?12345678";?

//Vector de inicialización?

privado?{?0x12,?0x34,?0x56,?0x78,? 0x90, ?0xAB, ?0xCD, ?0xEF?};

#region?DESEnCode?DES ¿cifrado

público?

{?

pToEncrypt =?HttpContext.Current.Server.UrlEncode(pToEncrypt);?

DESCryptoServiceProvider?des?=?new?DESCryptoServiceProvider();?

byte[]?inputByteArray ?=?Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);?

// ¿Crear la clave y el desplazamiento del objeto cifrado

// ¿O sin formato? ¿Método GetBytes usando el método ASCIIEncoding.ASCII?

// ¿Forzar la entrada de texto en inglés para la contraseña?

des.Key?=?ASCIIEncoding.ASCII.GetBytes(sKey);

des.IV?=?ASCIIEncoding.ASCII.GetBytes(sKey);?

MemoryStream?ms?=?new?MemoryStream();?

CryptoStream? cs?=?new?CryptoStream(ms,?des.CreateEncryptor(),?CryptoStreamMode.Write);?

cs.Write(inputByteArray,?0,?inputByteArray.Length);?

cs.FlushFinalBlock();?

StringBuilder?

foreach(byte?b?in?ms.ToArray())?

{

ret.AppendFormat("{0:X2}",?b);?

}?

ret.ToString();? p>

return.ToString();?

}

#endregion

//?

?

//

//?

resumen>?

//? ?Cadena a descifrar?

//? ?Clave de descifrado, 8 bytes, la misma que la clave de cifrado?

//? El descifrado devuelve la cadena descifrada si tiene éxito y devuelve la cadena de origen si falla?

#región?DESDeCode?DEScifrado DES?

público?

{?

//HttpContext.Current.Response.Write(pToDecrypt?+?"
"? +?sKey); ?

//HttpContext.Current.Response.End();?

DESCryptoServiceProvider?des?=?new?DESCryptoServiceProvider();?

byte[ ]?inputByteArray?=?new?byte[pToDecrypt.Length?/?2];?

for(int?x?=?0;?x?

{?

int?i?=?(Convert.ToInt32(pToDecrypt.Substring(x?*?2,?2),?16)); ?

inputByteArray[x]?(byte)i;?

}?

des.Key?=?ASCIIEncoding.ASCII.GetBytes(sKey); ?

des.IV?=?ASCIIEncoding.ASCII.GetBytes(sKey);?

MemoryStream?ms?=?new?MemoryStream();?

CryptoStream?cs?=?new?CryptoStream(ms,?des.CreateDecryptor(),?CryptoStreamMode.Write);?

cs.Write(inputByteArray,?0,?inputByteArray.Length);?

cs.FlushFinalBlock();?

StringBuilder?

return?HttpContext.Current.Server.UrlDecode(System.Text.Encoding.Default.GetString( ms.ToArray());?

}?

#endregion

}[php]?view?plain?copy?print?

clase?DES?

{?

var?$key;?

var?/ /offset?

function?DES(? $key,? $iv=0?)?{

//La longitud de la clave es 8, por ejemplo: 1234abcd?

$this->key?=?$key;?

if(? $iv?==?0?)?{

$this- >iv?=?$clave;?

$this->iv?=?$iv;?//mcrypt_create_iv(

?mcrypt_get_block_size?(MCRYPT_DES,?MCRYPT_MODE_CBC),?MCRYPT_DEV_RANDOM?);?

}?

}

función?encrypt($str)?{

/ ¿Cifrar y devolver una cadena hexadecimal en mayúsculas?

$size?=?mcrypt_get_block_size?(?MCRYPT_DES,?MCRYPT_MODE_CBC?);?

$str?=?$this->pkcs5Pad?(? $str,? $size ?);?

return?strtoupper(?bin2hex(?mcrypt_cbc(MCRYPT_DES, ? $this->key, ? $str,?MCRYPT_ENCRYPT, ? $this->iv?)?) ;?

}?

función?decrypt($str)?{

//¿Descifrar?

$strBin?$this->hex2bin (?strtolower(? $str?)?) ;?

$str?=?mcrypt_cbc(?MCRYPT_DES,?) ;?$this->key,? $strBin,?MCRYPT_DECRYPT,? ->iv?);?

$str?=?$this->pkcs5Unpad(? $str?);?

retorno?$str;?

}?

función?{?

$binData?=?"" ;?

para($i?=?0;?

for($i?=?0;?)$i?+=?2)?{

$binData =?chr(? hexdec(? substr(? $hexData,? $i,? 2?)?) ;?

}?

retorno?$binData;?

}

función ?{

$pad?(strlen(? $texto?)?$blocksize);?$blocksize);?

return?

Return $text .str_repeat(chr($pad), $pad);?

}?

función?pkcs5Unpad($texto)?{

$pad?= ?ord?(? $texto?{strlen?(? $texto?)??-?1}?) ;?

if($pad?>?strlen?(? $texto?)?

¿regresar?

if(strspn?(? $texto,?chr?(? $pad?),?strlen?(? $texto?)?-$pad?)$ pad)?$pad)?

regresar?

return "substr(? $texto,?0,? -?1? *? $pad?);?

}?

}?