Question

I have to remove an NSString (containing some confidential data) from memory but not only by setting it to nil, but by nullifying it's bytes. What I've tried so far is:

NSString *str = @"test";
NSLog(@"original string:%@", str);
CFStringRef ref = (__bridge CFStringRef)str;
const char * strPtr = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);
memset(strPtr, 0, [str lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);
NSLog(@"cleared string:%@", str);

but the function CFStringGetCStringPtr is returning NULL so it crashes at the line with the memset. Apple says here that in some cases it is normal for that function to return NULL, but then I don't know how to solve this.

Thanks in advance

Was it helpful?

Solution

Don't store confident data as strings. You can't remove them from memory easily.

If possible, use NSMutableData to store confident data, instead.

OTHER TIPS

Try This:

NSMutableString *str = [NSMutableString stringWithString:@"test"];

    NSLog(@"original string:%@", str);

    CFStringRef ref = ( CFStringRef)str;

    CFIndex stringLength = CFStringGetLength(ref), usedBytes = 0L;

    const char * strPtr = NULL;

    strPtr = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8);

    char *freeUTF8StringPtr = NULL;

    for(CFIndex idx = 0L; (strPtr != NULL) && (strPtr[idx] != 0); idx++) 
    {
        if(strPtr[idx] >= 128) { strPtr = NULL; }
    }

    if((strPtr == NULL) && ((freeUTF8StringPtr = malloc(stringLength + 1L)) != NULL)) 
   {

    CFStringGetBytes(ref, CFRangeMake(0L, stringLength), kCFStringEncodingUTF8, '?', false, (UInt8*)freeUTF8StringPtr, stringLength, &usedBytes);
        freeUTF8StringPtr[usedBytes] = 0;
        strPtr = (const char *)freeUTF8StringPtr;

    }

    NSUInteger memorySize=[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

    NSLog(@"cleared string:%@", str);

I have tried something like this below:-

NSMutableString *str = @"test";
NSLog(@"original string:%@", str);
CFStringRef ref = (__bridge CFStringRef)str;//kCFStringEncodingUTF16
const char * strPtr = CFStringGetCStringPtr(ref, kCFStringEncodingUTF16);
NSUInteger memorySize=[str lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"cleared string:%d", memorySize);


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