Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3DES Encryption / Decryption using ECB in iOS

i'm making an application , in which i have to encrypt a string using 3DES encryption in ECB mode. i m using "mykey" as a key.

+ (NSData *)tripleDesEncryptData:(NSData *)inputData
                             key:(NSData *)keyData
                           error:(NSError **)error
{
NSParameterAssert(inputData);
NSParameterAssert(keyData);

size_t outLength;

NSAssert(keyData.length == kCCKeySize3DES, @"the keyData is an invalid size");

NSMutableData *outputData = [NSMutableData dataWithLength:(inputData.length  +  kCCBlockSize3DES)];

CCCryptorStatus
    result = CCCrypt(kCCEncrypt, // operation
                     kCCAlgorithm3DES, // Algorithm
                     0, // options
                     keyData.bytes, // key
                     keyData.length, // keylength
                     nil,// iv
                     inputData.bytes, // dataIn
                     inputData.length, // dataInLength,
                     outputData.mutableBytes, // dataOut
                     outputData.length, // dataOutAvailable
                     &outLength); // dataOutMoved

    if (result != kCCSuccess) {
        if (error != NULL) {
            *error = [NSError errorWithDomain:@"com.your_domain.your_project_name.your_class_name."
                                         code:result
                                     userInfo:nil];
        }
        return nil;
    }
    [outputData setLength:outLength];
    NSLog(@"here is my output %@",outputData);
    return outputData;
}

i am getting an exception because of invalid Key size. (i'm using this 'mykey' as my key). I'm not expert in encryption. Any kind of Help will be highly appreciated.

like image 759
user2530884 Avatar asked Mar 20 '26 09:03

user2530884


1 Answers

You're getting "invalid key size" because, well, your key is an invalid size. I'm not sure what else you were expecting the system to tell you. The 3DES algorithm expects a key size of 24 bytes and "mykey" is too short.

Even apart from the length issue, in general it is a bad idea to directly use strings as cryptographic keys. Instead you should use an accepted password-to-key algorithm such as PBKDF2.

like image 60
zindorsky Avatar answered Mar 22 '26 01:03

zindorsky