Search code examples
c#phpencryptioncryptographybouncycastle

Encrypt and Decrypt using Bouncy Castle in c# and php


I am using the bouncy castle and the following code in c# to encrypt and decrypt data in c#

public static string BCEncrypt(string input)
{
    string keyString = "mysecretkey12345";
    string keyStringBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyString));
    byte[] inputBytes = Encoding.UTF8.GetBytes(input);
    byte[] iv = new byte[16]; 

    //Set up
    AesEngine engine = new AesEngine();
    CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding());
   //PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
   KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64));
   ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);

   // Encrypt
   cipher.Init(true, keyParamWithIV);
   byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
   int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
   cipher.DoFinal(outputBytes, length); //Do the final block
   return Convert.ToBase64String(outputBytes);
}

public static string BCDecrypt(string input)
{
    string keyString = "mysecretkey12345";
    string keyStringBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyString));
    byte[] inputBytes = Encoding.UTF8.GetBytes(input);
    byte[] iv = new byte[16];
    //Set up
    AesEngine engine = new AesEngine();
    CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
    KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64));
    ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);

    //Decrypt            
    byte[] outputBytes = Convert.FromBase64String(input);
    cipher.Init(false, keyParamWithIV);
    byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
    int length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
    cipher.DoFinal(comparisonBytes, length); //Do the final block
    return System.Text.Encoding.UTF8.GetString(comparisonBytes, 0, comparisonBytes.Length);
}

This is the code php code I am using:

<?
    function encrypt($input, $key) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); 
        $input = Security::pkcs5_pad($input, $size); 
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');  
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND); 
        mcrypt_generic_init($td, $key, $iv); 
        $data = mcrypt_generic($td, $input); 
        mcrypt_generic_deinit($td); 
        mcrypt_module_close($td); 
        $data = base64_encode($data); 
        return $data; 
   } 

   function pkcs5_pad ($text, $blocksize) { 
       $pad = $blocksize - (strlen($text) % $blocksize); 
       return $text . str_repeat(chr($pad), $pad); 
   }

   function decrypt($sStr, $sKey) {
       $decrypted= mcrypt_decrypt(
          MCRYPT_RIJNDAEL_128,
          $sKey, 
          base64_decode($sStr), 
          MCRYPT_MODE_ECB
       );
       $dec_s = strlen($decrypted); 
       $padding = ord($decrypted[$dec_s-1]); 
       $decrypted = substr($decrypted, 0, -$padding);
       return $decrypted;
   }

   echo "Input: " . $_REQUEST["inp"] . "<br>Decrypt: ". decrypt($_REQUEST["inp"], 'mysecretkey12345')."<br>";
   ?>

When I try to encrypt a short string using c# such as "greatscott" I get the following result: dSk7z0F4JYsc0zhl95+yMw==

This then decrypts ok using the php code.

However when I try to encrypt a longer string using the c# code such as "this is a very long string" I get the following result: xcL4arrFD8Fie73evfHjvUjNEmZrA9h6SmO0ZRE82Hw=

And this does not decrypt. If I try to encrypt the same string "this is a very long string" via the php encrypt function I get xcL4arrFD8Fie73evfHjva6yJyeUOrB8IudISDhQk24=

So the first half of the encrypted string is the same but the second half is not. This makes me think that I have got the padding incorrect or something.

Any advice would be appreciated.

Thanks


Solution

  • Thanks for the suggestions Luke and James.

    I am now using openssl for encryption and decryption in PHP and I am generating a random IV and passing it back and forward between the systems for decryption.

    This is the code I am now using:

    c#

    public static string BCEncrypt(string input, out string iv_base64)
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        SecureRandom random = new SecureRandom();
        byte[] iv = new byte[16];
        random.NextBytes(iv);
        iv_base64 = Convert.ToBase64String(iv);
        string keyString = "mysecretkey12345";
        string keyStringBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyString));
    
        //Set up
        AesEngine engine = new AesEngine();
        CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding());
        KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64));
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
    
        // Encrypt
        cipher.Init(true, keyParamWithIV);
        byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
        int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
        cipher.DoFinal(outputBytes, length); //Do the final block
        return Convert.ToBase64String(outputBytes);
    }
    
    public static string BCDecrypt(string input, string iv_base64)
    {
        string keyString = "mysecretkey12345";
        string keyStringBase64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyString));
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        byte[] iv = Convert.FromBase64String(iv_base64);
        //Set up
        AesEngine engine = new AesEngine();
        CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding());
        KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64));
        ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16);
    
        //Decrypt            
        byte[] outputBytes = Convert.FromBase64String(input);
        cipher.Init(false, keyParamWithIV);
        byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)];
        int length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0);
        cipher.DoFinal(comparisonBytes, length); //Do the final block
        return Encoding.UTF8.GetString(comparisonBytes, 0, comparisonBytes.Length);
    }
    

    The PHP side look like this:

    $iv = base64_decode($iv_base64);
    $method = "aes-128-cbc";
    $password = "mysecretkey12345";
    $decrypted = openssl_decrypt($data, $method, $password,0, $iv);
    

    And to generate the iv and encrypt a string in PHP I am using:

    $iv = openssl_random_pseudo_bytes(16)
    $encrypted = openssl_encrypt("something interesting", $method, $password,0,$iv);
    

    So I am now able to encrypt in C# or PHP and decrypt in C# or PHP.

    I am passing the base 64 encoded iv and encrypted string between the two systems using https.

    Any comments on this solution? (Security or otherwise?)