Question

I am trying to decrypt a string that was first encrypted using des in ecb mode, and then encoded in base64.

This is my code:

+ (NSString *)decrypt:(NSString *)encryptedText
{
    NSString *key = @"12345678";
    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:encryptedText options:0];
    size_t numBytesDecrypted = 0;
    size_t bufferSize = [decodedData length] + kCCBlockSizeDES;
    void *buffer = malloc(bufferSize);
    char keyPtr[kCCKeySizeDES+1]; // room for terminator (unused)
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];


    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                      kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding | kCCOptionECBMode,
                                      keyPtr,
                                      kCCKeySizeAES256,
                                      NULL /* initialization vector (optional) */,
                                      [decodedData bytes], [decodedData length], /* input */
                                      buffer,       bufferSize, /* output */
                                      &numBytesDecrypted);

    NSData *val = [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    return [[NSString alloc] initWithData:val encoding:NSUTF8StringEncoding];
}

However I am getting a nil string in return...any ideas?

Was it helpful?

Solution

You are using DES but are specifying the key size as: kCCKeySizeAES256 in the call to: CCCrypt.

There are so many things wrong with this code from a security standpoint, don't use this in a real app. This is no longer best practice. Among other things the password should be converted to key with a Password-Based Key Derivation Function such as PBKDF2. Also using DES and ECB mode is a weaknesses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top