Creating a secure file name from NSString?

Is there a way to take NSString and turn it into a safe version that can be used as a file name for saving in the User Documents folder on the iPhone.

I am currently doing something like this:

NSString *inputString = @"This is sample text which may have funny chars and spaces in."; NSInteger len = [inputString length]; NSString *newFilename = [[inputString substringToIndex:MIN(20, len)] stringByAppendingPathExtension:@"txt"]; 

Currently this leaves me with something like:

 This is sample text .txt 

You must ensure that characters that are not allowed in file names are also deleted.

+6
source share
3 answers

You will probably have some sort of regular expression or something else. Just because using an except filter is too dangerous (you may skip some illegal characters).

Therefore, I recommend that you use RegexKitLite (http://regexkit.sourceforge.net/RegexKitLite/) in combination with the following line of code:

 inputString = [inputString stringByReplacingOccurencesOfRegex:@"([^A-Za-z0-9]*)" withString:@""]; 

This will replace all characters except AZ, az and 0-9 =)!

+5
source

You can also do this in an old fashioned way instead of using a regex:

 NSString* SanitizeFilename(NSString* filename) { NSMutableString* stripped = [NSMutableString stringWithCapacity:filename.length]; for (int t = 0; t < filename.length; ++t) { unichar c = [filename characterAtIndex:t]; // Only allow az, AZ, 0-9, space, - if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == ' ' || c == '-') [stripped appendFormat:@"%c", c]; else [stripped appendString:@"_"]; } // No empty spaces at the beginning or end of the path name (also no dots // at the end); that messes up the Windows file system. return [stripped stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; } 
+3
source

If you really need a secure random file name, just use SecRandomCopyBytes for the required length and base64-encode.

-1
source

Source: https://habr.com/ru/post/894741/


All Articles