Search code examples
c#iosxcoderijndael

How can i decrypt file in ios that was encrypted in c# using Rijndael


I have an application in C# that encrypt my files with AES algorithm with this method:

private static void encryptFile(string inputFile, string outputFile, string strKey)
{
  try
  {
    using (RijndaelManaged aes = new RijndaelManaged())
    {
      byte[] key = Encoding.UTF8.GetBytes(strKey);
      byte[] IV = Encoding.UTF8.GetBytes(strKey);

      using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create))
      {
        using (ICryptoTransform encryptor = aes.CreateEncryptor(key, IV))
        {
          using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write))
          {
            using (FileStream fsIn = new FileStream(inputFile, FileMode.Open))
            {
              int data;
              while ((data = fsIn.ReadByte()) != -1)
              {
                cs.WriteByte((byte)data);
              }
            }
          }
        }
      }
    }
  }
  catch (Exception ex)
  {
    Debug.WriteLine(ex.Message);
  }
}

The file is encrypted without an issue.

Then I want to decrypt the encrypted file with my Android (2.2) application. So I do this:

private void decriptFile() throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException, IOException {
        //byte[] docBytes = serialize(myDoc);
        byte[] b = new byte[0];
        try {
            Resources res = getResources();
            InputStream in_s = res.openRawResource(R.raw.output27);

            b = new byte[in_s.available()];
            in_s.read(b);
            //txtHelp.setText(new String(b));
        } catch (Exception e) {
            // e.printStackTrace();
            //txtHelp.setText("Error: can't show help.");
        }

        //byte[] dataBytes = FileUtils.readFileToByteArray(File file);
        byte[] key = new byte[0];
        try {
           // key = ("HR$2pIjHR$2pIj12").getBytes("UTF-8");
            key = ("HR$2pIjHR$2pIj12").getBytes("UTF-8");
            Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec k = new SecretKeySpec(key, "AES");
            IvParameterSpec iv = new IvParameterSpec(key);
            c.init(Cipher.DECRYPT_MODE, k, iv);

            // IllegalBlockSizeException Occurred

            //File folder = new File(Environment.getExternalStorageDirectory(),
                    //"test");
            File folder = new File("/sdcard",
                    "test");
            if (!folder.exists()) {
                folder.mkdir();
            }

            byte[] decryptedDocBytes = c.doFinal(b);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(folder.getPath()+"/test.epub"));
            bos.write(decryptedDocBytes);
            bos.flush();
            bos.close();
            //DocumentsContract.Document decryptedDoc = (DocumentsContract.Document)deserialize(decryptedDocBytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //IvParameterSpec iv = new IvParameterSpec(key);



        //And my serialize/deserialize methods:
    }

This time decryption works fine.For decrypting same file in Objective C I am using the following method:

- (NSData *)decrypt:(NSData *)plainText key:(NSData *)aSymmetricKey padding:(CCOptions *)pkcs7
{
    //return [self doCipher:plainText key:aSymmetricKey context:kCCDecrypt padding:pkcs7];
    return [self doCipher2:plainText iv:[self generateRandomIV:128] key:aSymmetricKey context:kCCDecrypt error:nil];
}

- (NSData *)doCipher2:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt // kCCEncrypt or kCCDecrypt
               error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       0, //kCCOptionPKCS7Padding,
                       symmetricKey.bytes,
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);

    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }

    return dataOut;
}

This time no luck.What might be the problem?? Any help would be appreciated.


Solution

  • In the Android version you specify PKCS5Padding but no padding it the iOS version. Note that PKCS5Padding andPKCS7Padding amount to the same thing, there is just a definition difference.

    Change:

    0, //kCCOptionPKCS7Padding,
    

    to

    kCCOptionPKCS7Padding,