IOS中的AES解密没有给出确切的结果

时间:2015-06-26 06:49:20

标签: c# ios encryption cryptography

我试图在IOS中解密我的文件。该文件在C#应用程序中使用AES加密。

这是我的IOS解密方法:

- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv
{
    NSLog(@"inside AES128Operation");
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    if (iv) {
        [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    }

    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [self bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);

    if (cryptStatus == kCCSuccess) {
         return [NSData dataWithBytes:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

我使用它的方式:

NSString *strKey = MyKey;
NSString *strIv = MyIV;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *pathLocal_encrypted = [documentsDir stringByAppendingPathComponent:@"encrypted.file"];

NSData *data_encrpted = [[NSFileManager defaultManager] contentsAtPath:pathLocal_encrypted];

NSData *decryptedData = [data_encrpted AES128DecryptedDataWithKey:strKey iv:strIv];

IV是8字节向量。 最终解密的文件无法读取或严重解密。 我还尝试使用" AES128Operation"在ios应用程序中加密/解密。一些测试文件上的方法,它运行良好,但不知道为什么它不能解密C#加密文件。

解密在C#中运行良好,使用此代码(相同文件,相同iv,相同,密钥):

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }

    private static byte[] DecryptBytes(SymmetricAlgorithm alg, byte[] message)
    {
        if ((message == null) || (message.Length == 0))
        {
            return message;
        }
        using (var stream = new MemoryStream())
        {
            using (var decryptor = alg.CreateDecryptor())
            using (var encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
            {
                encrypt.Write(message, 0, message.Length);
                encrypt.FlushFinalBlock();
            }
            return stream.ToArray();
        }
    }
                path = openFileDialog1.FileName;
                byte[] encMessage = StreamFile(path);
                byte[] decMessage; 

                byte[] rkey = GetBytes(Mykey);
                byte[] riv = GetBytes(MyIv);
                using (var rijndael = new RijndaelManaged())
                {
                    rijndael.Key = rkey;
                    rijndael.IV = riv;
                    decMessage = DecryptBytes(rijndael, encMessage);
                }

由于答案的建议我试过这个,但仍然没有希望:

    NSData *key = [NSData dataWithData:[strKey dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *iv = [NSData dataWithData:[strIv dataUsingEncoding:NSUTF8StringEncoding]];
    NSData *decryptedData = [self doCipher:data_encrpted iv:iv key:key context:kCCDecrypt];

和新功能:

- (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt
{

    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;    // Number of bytes moved to buffer.
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

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


        NSLog(@"CCCrypt status: %d", ccStatus);


    dataOut.length = cryptBytes;
    NSLog(@"CCCrypt ataOut.length: %d", dataOut.length);
    return dataOut;
}

这是C#中的加密\解密设置:

   public RijndaelManaged GetRijndaelManaged(string secretKey, string iv)
    {
        var keyBytes = new byte[16];
        var secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
        Array.Copy(secretKeyBytes, keyBytes, Math.Min(keyBytes.Length, secretKeyBytes.Length));

        var ivBytes = new byte[16];
        var secretIvBytes = Encoding.UTF8.GetBytes(iv);
        Array.Copy(secretIvBytes, ivBytes, Math.Min(ivBytes.Length, secretIvBytes.Length));

        return new RijndaelManaged
        {
            Mode = CipherMode.CBC,
            Padding = PaddingMode.PKCS7,
            KeySize = 128,
            BlockSize = 128,
            Key = keyBytes,
            IV = ivBytes
        };
    }

    public byte[] Encrypt(byte[] plainBytes, RijndaelManaged rijndaelManaged)
    {
        return rijndaelManaged.CreateEncryptor()
            .TransformFinalBlock(plainBytes, 0, plainBytes.Length);
    }

    public byte[] Decrypt(byte[] encryptedData, RijndaelManaged rijndaelManaged)
    {
        return rijndaelManaged.CreateDecryptor()
            .TransformFinalBlock(encryptedData, 0, encryptedData.Length);
    }

2 个答案:

答案 0 :(得分:1)

正如文档所说的C#默认模式(AesManaged.Mode属性):

One of the enumeration values that specifies the block cipher mode to use for encryption. The default is CBC.

因此,在ios中,您还必须使用CBC模式解密数据。

从您的解密代码中删除kCCOptionECBMode

至于填充:

  

属性值类型:System.Security.Cryptography.PaddingMode之一   枚举值,指定要应用的填充类型。   默认值为PKCS7。

因此,请检查您的解密代码是否有正确的参数

答案 1 :(得分:1)

AES的iv与块大小相同:128位(16字节),问题是:" IV是8字节向量"这是不正确的。

由于您使用的是静态模式,因此该模式应为CBC,但代码指定kCCOptionECBMode,删除此项,iOS上的默认值(Common Crypto)为CBC模式。

请注意,RijndaelManaged默认为CBC模式和PKCS#7填充。但是,如果未明确设置密钥大小,则由提供的密钥的长度确定,并且空填充到支持的密钥长度。最好在RijndaelManaged中使用KeySize参数(以位为单位)明确设置此项。

AES的块大小为128位,RijndaelManaged支持多种块大小,AESManaged是AES加密的更好选择。这可能不是问题。最好在RijndaelManaged中明确设置此项,并使用值为128的BlockSize参数。