本文介绍了PHP加密兼容C#加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个c#加密代码:

  public class Cryptor_Engine 
{
///< ;总结>
///使用双加密方法加密字符串。返回加密密文文本
///< / summary>
///< param name =toEncrypt>要加密的字符串< / param>
///< param name =useHashing>使用哈希?发送到额外的安全性< / param>
///< returns>< / returns>
public static string Encrypt(string toEncrypt,string key,bool useHashing)
{
byte [] keyArray;
byte [] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
if(useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateEncryptor();
byte [] resultArray = cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray,0,resultArray.Length);
}
///< summary>
///使用双加密方法DeCrypt一个字符串。返回一个解密的清除字符串
///< / summary>
///< param name =cipherString>加密字符串< / param>
///< param name =useHashing>您是否使用哈希加密此数据?传真为yes< / param>
///< returns>< / returns>
public static string Decrypt(string cipherString,string key,bool useHashing)
{
byte [] keyArray;
byte [] toEncryptArray = Convert.FromBase64String(cipherString);

System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
//从配置文件获取密钥以打开锁定!
// string key =(string)settingsReader.GetValue(SecurityKey,typeof(String));

if(useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);

TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;

ICryptoTransform cTransform = tdes.CreateDecryptor();
byte [] resultArray = cTransform.TransformFinalBlock(toEncryptArray,0,toEncryptArray.Length);

tdes.Clear();
返回UTF8Encoding.UTF8.GetString(resultArray);
}
}

上述代码根据提供的内容对文本进行加密和解密键。我需要一个兼容的PHP代码,将给我与上述算法相同的密钥?可以使用php和c#来加密文本吗?

解决方案

加密



首先,如果 $ useHashing 为true,我们需要在 $ key 上运行MD5算法

 函数加密($ toEncrypt,$ key,$ useHashing){
if($ useHashing){
$ key = md5($ key);
}

接下来,我们需要使用PKCS7算法来填充它。使用PKCS7,字符串的最后一个字节指定填充长度,因此我们需要确定需要多少填充,然后添加。

  $ blockSize = mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_ECB); 
$ len = strlen($ toEncrypt);
$ pad = $ blockSize - ($ len%$ blockSize);
$ toEncrypt。= str_repeat(chr($ pad),$ pad);

接下来,我们使用Mcrypt扩展名进行加密。

  $ encrypted = mcrypt_encrypt(MCRYPT_3DES,$ key,$ toEncrypt,MCRYPT_MODE_ECB); 

最后,将加密的字符串编码为Base64。

  return base64_encode($ encrypted); 

所以完整的功能如下所示:

 函数加密($ toEncrypt,$ key,$ useHashing){
if($ useHashing){
$ key = md5($ key);
}

$ blockSize = mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_ECB);
$ len = strlen($ toEncrypt);
$ pad = $ blockSize - ($ len%$ blockSize);
$ toEncrypt。= str_repeat(chr($ pad),$ pad);

$ encrypted = mcrypt_encrypt(MCRYPT_3DES,$ key,$ toEncrypt,MCRYPT_MODE_ECB);

返回base64_encode($ encrypted);
}



解密



首先,您收到加密密码为Base64,因此您需要对其进行解码。

 函数解密($ cipherString,$ key,$ useHashing){
$ decoded = base64_decode($ cipherString);
...

然后,如果 useHashing 是真的,我们需要在密钥上运行md5算法。

  if($ useHashing){
$ key = md5($ key);
}

现在我们有我们的键和解码字符串,我们实际上可以解密数据。

  $ decryptpted = mcrypt_decrypt(MCRYPT_3DES,$ key,$ decoding,MCRYPT_MODE_ECB); 

$ decryptpted 包含解密的字符串,带填充。要删除填充,我们需要找到最后一个字节的整数值:

  $ len = strlen($ decryptpted); 
$ pad = ord($ decryptpted [$ len-1]);

现在 $ pad 是一个整数,指定填充有多大,所以只需在填充之前返回字符串的一部分。

 返回substr($ decryptpted,0, $ len  -  $ pad); 

所以把它放在一起,我们有:



函数解密($ cipherString,$ key,$ useHashing){
$ decoded = base64_decode($ cipherString); $ $ $ $ $ $

if($ useHashing){
$ key = md5($ key);
}

$ decryptpted = mcrypt_encrypt(MCRYPT_3DES,$ key,$ decoding,MCRYPT_MODE_ECB);

$ len = strlen($ decryptpted);
$ pad = ord($ decryptpted [$ len-1]);

return substr($ decryptpted,0,$ len - $ pad);
}



安全性



如果可能,您应该。


i have this c# encryption code:

 public class Cryptor_Engine
{
    /// <summary>
    /// Encrypt a string using dual encryption method. Return a encrypted cipher Text
    /// </summary>
    /// <param name="toEncrypt">string to be encrypted</param>
    /// <param name="useHashing">use hashing? send to for extra secirity</param>
    /// <returns></returns>
    public static string Encrypt(string toEncrypt, string key, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    /// <summary>
    /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
    /// </summary>
    /// <param name="cipherString">encrypted string</param>
    /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
    /// <returns></returns>
    public static string Decrypt(string cipherString, string key, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString);

        System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
        //Get your key from config file to open the lock!
        //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        tdes.Clear();
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
}

The above code encrypts and decrypts text based on a provided key. i need a compatible php code that will give me the same key as the above algorithm? Will be possible to use both php and c# to have similar encrypted text?

解决方案

Encryption

Firstly, if $useHashing is true, we need to run the MD5 algorithm on $key

function encrypt($toEncrypt, $key, $useHashing) {
    if ($useHashing) {
        $key = md5($key);
    }

Next, we need to pad it using the PKCS7 algorithm. With PKCS7, the last byte of the string specifies the padding length, so we need to work out how much padding is required, and then add it.

    $blockSize = mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
    $len = strlen($toEncrypt);
    $pad = $blockSize - ($len % $blockSize);
    $toEncrypt .= str_repeat(chr($pad), $pad);

Next, we do the encryption using the Mcrypt extension.

    $encrypted = mcrypt_encrypt(MCRYPT_3DES, $key, $toEncrypt, MCRYPT_MODE_ECB);

Lastly, encode the encrypted string as Base64.

    return base64_encode($encrypted);

So the complete function looks like:

function encrypt($toEncrypt, $key, $useHashing) {
    if ($useHashing) {
        $key = md5($key);
    }

    $blockSize = mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
    $len = strlen($toEncrypt);
    $pad = $blockSize - ($len % $blockSize);
    $toEncrypt .= str_repeat(chr($pad), $pad);

    $encrypted = mcrypt_encrypt(MCRYPT_3DES, $key, $toEncrypt, MCRYPT_MODE_ECB);

    return base64_encode($encrypted);
}

Decryption

Firstly you receive the encrypted cipher as Base64, so you need to decode it.

function decrypt($cipherString, $key, $useHashing) {
    $decoded = base64_decode($cipherString);
    ...

Then, if useHashing is true, we need to run the md5 algorithm on the key.

    if ($useHashing) {
        $key = md5($key);
    }

Now we have our key and decoded string, we can actually decrypt the data.

    $decrypted = mcrypt_decrypt(MCRYPT_3DES, $key, $decoded, MCRYPT_MODE_ECB);

$decrypted contains the decrypted string, with padding. To remove the padding we need to find the integer value of the last byte:

    $len = strlen($decrypted);
    $pad = ord($decrypted[$len-1]);

Now $pad is an integer which specifies how large the padding is, so simply return the part of the string before the padding.

    return substr($decrypted, 0, $len - $pad);

So putting it all together, we have:

function decrypt($cipherString, $key, $useHashing) {
    $decoded = base64_decode($cipherString);

    if ($useHashing) {
        $key = md5($key);
    }

    $decrypted = mcrypt_encrypt(MCRYPT_3DES, $key, $decoded, MCRYPT_MODE_ECB);

    $len = strlen($decrypted);
    $pad = ord($decrypted[$len-1]);

    return substr($decrypted, 0, $len - $pad);
}

Security

If at all possible, you should look at using AES, rather than 3DES and a more secure cipher mode than ECB.

这篇关于PHP加密兼容C#加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:45