如何在php中解密C#代码

时间:2013-07-22 04:56:58

标签: c# php

我用Cij编写了一个代码,用于使用Rijndael算法进行加密。现在我想解密php中的加密值。我尝试了但是没有得到我加密的确切字符串。 以下是C#中的加密代码。

public string Encrypt(string textToBeEncrypted, string Password) 
{ 

    RijndaelManaged RijndaelCipher = new RijndaelManaged(); 
    ICryptoTransform Encryptor = null; 
    byte[] plainText = null; 
    try 
    { 
        byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); 
        PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt); 
        //Creates a symmetric encryptor object. 
        Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16)); 
        plainText = Encoding.Unicode.GetBytes(textToBeEncrypted); 

    } 
    catch (Exception ex) 
    { 
        string str = "Method Name: " + MethodBase.GetCurrentMethod().Name + " | Description: " + ex.Message + ex.InnerException; 
        log.Error(str); 

    } 
    return Convert.ToBase64String(Encryptor.TransformFinalBlock(plainText, 0, plainText.Length)); 

} 

php中的解密代码是

function decryptData($value){
    $key = "same key used in above c# code";
    $crypttext = $value;
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
    return trim($decrypttext); 
}

我有c#代码进行解密,如下所示

public string Decrypt(string TextToBeDecrypted, string Password) { 
RijndaelManaged RijndaelCipher = new RijndaelManaged(); 
string DecryptedData; 
byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted); 
byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString()); 
//Making of the key for decryption 
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt); 
//Creates a symmetric Rijndael decryptor object. 
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32),SecretKey.GetBytes(16)); 
byte[] plainText = Decryptor.TransformFinalBlock(EncryptedData, 0, EncryptedData.Length); 
//Converting to string 
DecryptedData = Encoding.Unicode.GetString(plainText); 
return DecryptedData; 
} 

但是在PHP.Key中需要相同的代码将与用于加密的相同。请建议......

1 个答案:

答案 0 :(得分:1)

以下检查可以解决您的问题。

  1. 您需要具有相同的加密和解密模式。在PHP代码中,您使用ECB模式进行解密。如果您在C#中使用相同的ECB模式,请检查。

  2. 在c#中生成密钥和iv用于加密,并使用相同的值进行解密。在php解密代码中生成密钥或iv。

  3. 在解密之前解码base64字符串