简体   繁体   English

我如何使用Rijndael在以C#加密的ios中解密文件

[英]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: 我在C#中有一个应用程序,使用此方法使用AES算法加密我的文件:

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. 然后,我想用我的Android(2.2)应用程序解密加密的文件。 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 CI am using the following method: 这次解密工作正常,要使用以下方法在Objective CI中解密相同文件:

- (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. 任何帮助,将不胜感激。

In the Android version you specify PKCS5Padding but no padding it the iOS version. 在Android版本中,您指定PKCS5Padding但在iOS版本中未填充它。 Note that PKCS5Padding and PKCS7Padding amount to the same thing, there is just a definition difference. 请注意, PKCS5PaddingPKCS7Padding的作用相同,只是定义不同。

Change: 更改:

0, //kCCOptionPKCS7Padding,

to

kCCOptionPKCS7Padding,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM