Convert C # Rijndael function to php function

I am trying to convert a C # function to PHP.

Here is the C # function:

public string Encrypt(string Value) { string RetVal = ""; if(Value != string.Empty && Value != null) { MemoryStream Buffer = new MemoryStream(); RijndaelManaged RijndaelManaged = new RijndaelManaged(); UnicodeEncoding UnicodeEncoder = new UnicodeEncoding(); byte[] KeyArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; byte[] IVArray = new Byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; try { byte[] ValueBytes = UnicodeEncoder.GetBytes(Value); CryptoStream EncryptStream = new CryptoStream(Buffer, RijndaelManaged.CreateEncryptor(KeyArray, IVArray), CryptoStreamMode.Write); EncryptStream.Write(ValueBytes, 0, ValueBytes.Length); EncryptStream.FlushFinalBlock(); // Base64 encode the encrypted data RetVal = Convert.ToBase64String(Buffer.ToArray()); } catch { throw; } } return RetVal; } 

and here is my attempt in PHP:

 function EncryptString ($cleartext) { $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); $key128 = '111111111111111111111111111'; $iv = '111111111111111111111111111'; if (mcrypt_generic_init($cipher, $key128, $iv) != -1) //Parameter iv will be ignored in ECB mode { $cipherText = mcrypt_generic($cipher,$cleartext ); mcrypt_generic_deinit($cipher); $encrypted = (bin2hex($cipherText)); return base64_encode($encrypted); } } 

Currently, when I encode the test phrase "test" using these two functions, I get different values. It looks like the PHP version takes a string for the values ​​of $key and $iv , where the C # version takes an array of bytes.

How do I change my PHP function to mimic a C # function?

[edit] C # function is a third party, and I do not have access to change it; I need to write an equivalent in PHP to encode a given string in the same way

+4
source share
2 answers

Take a look at the RijndaelManaged documentation and copy:

  • encryption mode (cbc)
  • block size
  • fill mode (pkcs # 7)

Please note that you can indent from other sources.

Now make sure that you use the same input for both sides. You can do this by printing the key, IV, and plain text in hexadecimal values. The key size and IV size must be the exact number of bits required by the algorithm. To get the same plain text, you need to use identical character-encoding with.

Finally, you need the same encoding of the ciphertext, but it seems like you got it.

+1
source

I would try using instead of line 27 1 this:

 $key128 = ''; for ( $i = 0; $i < 27; ++$i ) $key128 .= chr(1); $iv = $key128; // copy 

I'm not quite sure what these functions do, but it will turn your strings into byte arrays with a repeat of 1.

-1
source

All Articles