samedi 27 juin 2015

AES Decryption in IOS not giving the exact result

Im trying to Decrypt my file in IOS. the file is encrypted with AES in C# application.

this is my IOS Decryption Method :

- (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;
}

And the way im using it :

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 is a 8 Byte Vector. The final decrypted file is unreadable or badly decrypted. i also tried Encrypt/Decrypt inside ios application with "AES128Operation" method on some test file and it works well but dont know why it cant decrypt the C# encrypted file.

The Decryption Works well in C# with this code (same file , Same iv , Same ,Key):

    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);
                }

due to answer suggestion ive tried this one to but still no hope :

    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];

and the new function :

- (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;
}

this is the encryption\decryption setting inside 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);
    }

Aucun commentaire:

Enregistrer un commentaire