如何在php中解密C#代码

本文关键字:解密 代码 php | 更新日期: 2023-09-27 18:24:05

我用C#编写了一段代码,用于使用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中需要相同的代码。密钥将和用于加密的密钥相同。请提供建议。。。。

如何在php中解密C#代码

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

  1. 加密和解密需要使用相同的模式。在php代码中,您使用ECB模式进行解密。请检查您是否在C#中使用相同的ECB模式。

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

  3. 在php 中解密前解码base64字符串