//
//  DefaultPacketEncrypter.m
//  SFS2X
//
//  Created by Lapo on 01/06/15.
//  Copyright (c) 2015 A51 Integrated | http://a51integrated.com. All rights reserved.
//

#import "DefaultPacketEncrypter.h"
#import <CommonCrypto/CommonCryptor.h>
#import <CommonCrypto/CommonKeyDerivation.h>

@implementation DefaultPacketEncrypter

const CCAlgorithm kAlgorithm = kCCAlgorithmAES128;
const NSUInteger kAlgorithmKeySize = kCCKeySizeAES128;
const NSUInteger kAlgorithmBlockSize = kCCBlockSizeAES128;
const NSUInteger kAlgorithmIVSize = kCCBlockSizeAES128;
const NSString* kRNCryptManagerErrorDomain = @"DefaultPacketEncrypter";

-(id) initWithBitSwarm:(BitSwarmClient *)bsc
{
    self = [super init];
    
    if (self) {
        _bitSwarm = bsc;
    }
    
    return self;
}

-(NSData*) encode:(NSData*)data
{
    return [self process:data withOperation:kCCEncrypt];
}

-(NSData*) decode:(NSData*)data
{
    return [self process:data withOperation:kCCDecrypt];
}

//--- Private -------------------------------------------------

-(NSData*) process:(NSData*)data withOperation:(CCOperation)operation
{
    size_t outLength;
    NSMutableData* cipherData = [NSMutableData dataWithLength:data.length + kAlgorithmBlockSize];
    
    NSData* key = _bitSwarm.cryptoKey.key;
    NSData* iv = _bitSwarm.cryptoKey.iv;
    
    CCCryptorStatus result = CCCrypt
    (
     operation, // operation
     kAlgorithm, // Algorithm
     kCCOptionPKCS7Padding, // options
     key.bytes, // key
     key.length, // keylength
     iv.bytes,// iv
     data.bytes, // dataIn
     data.length, // dataInLength,
     cipherData.mutableBytes, // dataOut
     cipherData.length, // dataOutAvailable
     &outLength // dataOutMoved
     );
    
    if (result == kCCSuccess)
    {
        cipherData.length = outLength;
        return cipherData;
    }
    else
        return nil;
    
}

@end
