2013-07-22 85 views
0

我已經使用Rijndael算法在C#中編寫了一個用於加密的代碼。現在我想在php中解密加密的值。我試過,但沒有得到我加密的確切字符串。 以下是C#中的加密代碼。在PHP如何在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)); 

} 

解密代碼

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相同的代碼將是相同的。請建議....

+0

你能告訴一個例子'$ key'在PHP decrytion前的base64字符串? –

+0

似乎你base64它在你的非PHP代碼,不要忘了base64_decode在PHP中(除非我不記得正確的mcrypt params,我沒有用太多)。 –

+0

Hi @AmalMurali,$ key包含多達12個字符的字母ie.ABCDEFGPQRUV – pise

回答

1

以下檢查應該可以解決您的問題。

  1. 你需要有加密和decrytion.In PHP代碼相同的模式,你正在使用decryption.check ECB模式,如果您使用的是C#一樣ECB模式。

  2. 在c#中生成密鑰和iv以進行加密,並使用相同的值進行解密。在php解密代碼中生成密鑰或iv。

  3. 解碼