NSData to NSArray conversion as Strings without String interpretation - xcode

I have an NSData object whose contents are raw bytes looking something like this:
1e050014 c8d7b452 28f98c72 e95748b9 2801086b e85b07b9 2c010054 01000014
88c9b452 68878a72 e95748b9 2801086b e85707b9 20030154 10050014 a84bb552
c8299a72 e95748b9 2801086b e85307b9 2c010054
I'm trying to put these in a string array as is and this hasn't worked and returns an empty array:
NSData* data0 = [NSData dataWithContentsOfFile:str0];//this contains the bytes well
NSMutableArray *array = [NSMutableArray arrayWithCapacity:data0.length];
This doesn't work either:
const char* fileBytes = (const char*)[data0 bytes];
for (int i = 0; i < data0.length; i++) {
UInt8 byteFromArray = fileBytes[i];
[array addObject:#(byteFromArray)];
}
How can I put the raw bytes into a string array without interpreting the raw bytes as strings?

Related

AES Encryption is not working (Xcode)

I'm trying to encrypt string in Xcode to PHP with AES128 method by using following code:
Xcode
- (NSData*)AES256EncryptWithKey:(NSString*)key {
char keyPtr[kCCKeySizeAES256];
[key cStringUsingEncoding:NSASCIIStringEncoding];
NSString *iv = #"fdsfds85435nfdfs";
char ivPtr[kCCKeySizeAES128];
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSASCIIStringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, NULL,
keyPtr, kCCKeySizeAES256,
ivPtr,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
But when I run above coding, following result is not what I expect to be:
NSString *key = #"89432hjfsd891787";
NSData *plaintext = [[#"aaa0000000000000" dataUsingEncoding:NSASCIIStringEncoding] AES256EncryptWithKey: key];
NSString *mystring = [[NSString alloc] initWithData:plaintext encoding:NSASCIIStringEncoding];
NSLog(#"mystring %#", mystring);
OUTPUT is
uçó)â½S/èRÅ
What I want it something like that.
m9FNGM9IiwibWFjIjoiNmJkYzNmZTA5
Note: due to a coding error the keyPtr is not set to the key value, it becomes the value of the uninitialized memory.
You get "uçó)â½S/èRÅ" because you try to create a string from the data and there are a couple reasons this will not work.
Many data bytes do not map to printable ASCII characters or to any unicode character.
A data byte can be 0 (1 in 256 bytes on average will be 0x00) and that is a terminator for a "C" string so the string will be short.
There are two general conventions for encoding data into a string representation:
Hex-ascii where each data byte is encoded into two characters 0-9a-f.
Base64 where each 3 data data bytes are encoded into 4 ASCII characters.
You are probably looking for Base64 encoding:
NSString *mystring = [plaintext base64EncodedStringWithOptions:0];
Other errors in the code:
[key cStringUsingEncoding:NSASCIIStringEncoding]; The string may not be ASCII, better to use NSUTF8StringEncoding. Note that the output is not captured.
The keyPtr is never set to the key value, see above.
The key size id specified as 256-bits (32-bytes) but the key is 16 characters, use a key size that matched the key.
char ivPtr[kCCKeySizeAES128], an iv size is the block size not the key size: kCCBlockSizeAES128.
Looks like you want a Base64 encoded string.
NSString *mystring = [plaintext base64EncodedStringWithOptions:0];

compressed CGImage with CGImageDestination truncated after getting bytes

I want to get the compressed data from a CGImageRef to send it over a network connection.
To do so, i use a CGImageDestinationRef (CGImageDestinationCreateWithData).
After pulling the Data out of the CFDataRef Object the image misses a couple of rows at the bottom.
Here is what i do (cleaned for reading purpose...):
CFImageRef image = getTheImageRefIWant();
CFMutableDataRef pngData = CFDataCreateMutable (kCFAllocatorDefault, 0);
CGImageDestinationRef dataDest = CGImageDestinationCreateWithData (pngData, kUTTypePNG, 1, NULL);
CGImageDestinationAddImage (dataDest, image, NULL); //also tried this with options...
CGImageDestinationFinalize (dataDest);
CFIndex len = CFDataGetLength(pngData);
//copy data
unsigned char* m_image = malloc(len);
CFDataGetBytes (pngData, CFRangeMake(0,len), m_image);
//save data - for testing purpose
FILE *file = fopen("/path/test.png", "wb");
fwrite(m_image, 1, len, file);
//adding header and stuff - skipped here...
//send data
send(sockfd, m_image, len, 0);
If i use the CFData Object as NSData Object and save it to disk it does work:
NSData *data = [(NSData *)pngData autorelease];
[data writeToFile:#"/path/test.png" atomically:YES];
but if is use NSDatas byte method, it is the same (truncated image):
NSUInteger len = [data length];
m_image = malloc(len);
memcpy(m_image, (unsigned char*)[data bytes], len);
seems the data in CFData Object seems to be ok.
But how to get the bytes properly?
Thanks for any advice.
Have you either fflush()ed or fclose()d the file after writing it? Your data may just be buffered in memory.

How to convert an NSData into an NSString Hex string?

When I call -description on an NSData object, I see a pretty Hex string of the NSData object's bytes like:
<f6e7cd28 0fc5b5d4 88f8394b af216506 bc1bba86 4d5b483d>
I'd like to get this representation of the data (minus the lt/gt quotes) into an in-memory NSString so I can work with it.. I'd prefer not to call -[NSData description] and then just trim the lt/gt quotes (because I assume that is not a guaranteed aspect of NSData's public interface and is subject change in the future).
What's the simplest way to get this representation of an NSData object into an NSString object (other than calling -description)?
Keep in mind that any String(format: ...) solution will be terribly slow (for large data)
NSData *data = ...;
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i) {
[sbuf appendFormat:#"%02X", (NSUInteger)buf[i]];
}
If you need something more performant try this:
static inline char itoh(int i) {
if (i > 9) return 'A' + (i - 10);
return '0' + i;
}
NSString * NSDataToHex(NSData *data) {
NSUInteger i, len;
unsigned char *buf, *bytes;
len = data.length;
bytes = (unsigned char*)data.bytes;
buf = malloc(len*2);
for (i=0; i<len; i++) {
buf[i*2] = itoh((bytes[i] >> 4) & 0xF);
buf[i*2+1] = itoh(bytes[i] & 0xF);
}
return [[NSString alloc] initWithBytesNoCopy:buf
length:len*2
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
}
Swift version
private extension Data {
var hexadecimalString: String {
let charA: UInt8 = 0x61
let char0: UInt8 = 0x30
func byteToChar(_ b: UInt8) -> Character {
Character(UnicodeScalar(b > 9 ? charA + b - 10 : char0 + b))
}
let hexChars = flatMap {[
byteToChar(($0 >> 4) & 0xF),
byteToChar($0 & 0xF)
]}
return String(hexChars)
}
}
I agree on the solution not to call description which is to be reserved for debugging, so good point and good question :)
The easiest solution is to loop thru the bytes of the NSData and construct the NSString from it. Use [yourData bytes] to access the bytes, and build the string into an NSMutableString.
Here is an example by implementing this using a category of NSData
#interface NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces;
#end
#implementation NSData(Hex)
-(NSString*)hexRepresentationWithSpaces_AS:(BOOL)spaces
{
const unsigned char* bytes = (const unsigned char*)[self bytes];
NSUInteger nbBytes = [self length];
//If spaces is true, insert a space every this many input bytes (twice this many output characters).
static const NSUInteger spaceEveryThisManyBytes = 4UL;
//If spaces is true, insert a line-break instead of a space every this many spaces.
static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);
NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
for(NSUInteger i=0; i<nbBytes; ) {
[hex appendFormat:#"%02X", bytes[i]];
//We need to increment here so that the every-n-bytes computations are right.
++i;
if (spaces) {
if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:#"\n"];
else if (i % spaceEveryThisManyBytes == 0) [hex appendString:#" "];
}
}
return [hex autorelease];
}
#end
Usage:
NSData* data = ...
NSString* hex = [data hexRepresentationWithSpaces_AS:YES];
Just wanted to add that #PassKits's method can be written very elegantly using Swift 3 since Data now is a collection.
extension Data {
var hex: String {
var hexString = ""
for byte in self {
hexString += String(format: "%02X", byte)
}
return hexString
}
}
Or ...
extension Data {
var hex: String {
return self.map { b in String(format: "%02X", b) }.joined()
}
}
Or even ...
extension Data {
var hex: String {
return self.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
}
}
I liked #Erik_Aigner's answer the best. I just refactored it a bit:
NSData *data = [NSMutableData dataWithBytes:"acani" length:5];
NSUInteger dataLength = [data length];
NSMutableString *string = [NSMutableString stringWithCapacity:dataLength*2];
const unsigned char *dataBytes = [data bytes];
for (NSInteger idx = 0; idx < dataLength; ++idx) {
[string appendFormat:#"%02x", dataBytes[idx]];
}
In Swift you can create an extension.
extension NSData {
func toHexString() -> String {
var hexString: String = ""
let dataBytes = UnsafePointer<CUnsignedChar>(self.bytes)
for (var i: Int=0; i<self.length; ++i) {
hexString += String(format: "%02X", dataBytes[i])
}
return hexString
}
}
Then you can simply use:
let keyData: NSData = NSData(bytes: [0x00, 0xFF], length: 2)
let hexString = keyData.toHexString()
println("\(hexString)") // Outputs 00FF
Sadly there's no built-in way to produce hex from an NSData, but it's pretty easy to do yourself. The simple way is to just pass successive bytes into sprintf("%02x") and accumulate those into an NSMutableString. A faster way would be to build a lookup table that maps 4 bits into a hex character, and then pass successive nybbles into that table.
While it may not be the most efficient way to do it, if you're doing this for debugging, SSCrypto has a category on NSData which contains two methods to do this (one for creating an NSString of the raw byte values, and one which shows a prettier representation of it).
http://www.septicus.com/SSCrypto/trunk/SSCrypto.m
Seeing there is a Swift 1.2 snippet in the comments, here's the Swift 2 version since C style for loops are deprecated now.
Gist with MIT license and two simple unit tests if you care.
Here's the code for your convenience:
import Foundation
extension NSData {
var hexString: String {
let pointer = UnsafePointer<UInt8>(bytes)
let array = getByteArray(pointer)
return array.reduce("") { (result, byte) -> String in
result.stringByAppendingString(String(format: "%02x", byte))
}
}
private func getByteArray(pointer: UnsafePointer<UInt8>) -> [UInt8] {
let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: length)
return [UInt8](buffer)
}
}
Assuming you have already set:
NSData *myData = ...;
Simple solution:
NSString *strData = [[NSString alloc]initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strData);

Cocoa AES Encryption NSData and Bytearrays

I'm using the following code to encrypt files in cocoa:
- (NSData *)AES256EncryptWithKey:(NSString *)key
{
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted );
if( cryptStatus == kCCSuccess )
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free( buffer ); //free the buffer
return nil;
}
And wrote this for the connection to the file:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"foo" ofType:#"rtf"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSString *key = [withFileKey stringValue];
NSString *newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *encrypted = [newStr AES256EncryptWithKey:key];
NSLog(#"File encryption:%#", encrypted);
[filePathName setStringValue:filePath];
if (!data) {
NSLog(#"Unable to read file");
}
Basically what I did was first of all get the filepath of the file the user wants. Then convert the data in the file to a string. Then encrypt that string with the AES256EncryptWithKey: method. However, when I decrypt a plain text file for example, it returns a bunch of garbage like fonts and all that stuff, then the few lines I wrote. Something like this:
\ansicpg1252\cocoartf1138\cocoasubrtf100
{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset0 Menlo-Bold;}
{\colortbl;\red255\green255\blue255;}
\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\pardirnatural
\f0\fs24 \cf0 Hello my name is bobby bob\
\
\pard\tx560\pardeftab560\pardirnatural
\f1\b\fs22 \cf0 \CocoaLigature0 YAY!\
and I am awesome!!}
Shouldn't I be taking the data and then encrypting that (conversion to bytes), then convert the encrypted data and convert it to a string to display? I tried something like that but it didn't work. :(
Something like:
NSData *encryptedData = [data AES256EncryptWithKey:yourkey];
And then:
NSString *convertData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
?
Your help is greatly appreciated. Thanks!
Your code appears hard-coded to load foo.rtf. This looks like an RTF file. Where is the "plain text file" you're talking about?
EDIT We had a lot of discussion on this, so I wrote up a blog post about how to correctly use CCCrypt().

Trying to get bytes and append using NSMutableData for a video through Asset Library gives memory full error

I’m trying to upload a video of size 100MB through Asset Library. But when i try to use -(NSUInteger)getBytes:(uint8_t *)buffer fromOffset:(long long)offset length:(NSUInteger)length error:(NSError **)error of ALAssetRepresentation I get memory full error. I also need to put the data in buffer to NSData. How can i achieve that?
I tried this way:
Byte *buffer = (Byte*)malloc(asset.defaultRepresentation.size);
NSUInteger k = [asset.defaultRepresentation getBytes:buffer fromOffset: 0.0
length:asset.defaultRepresentation.size error:nil];
NSData *adata = NSData *adata = [NSData dataWithBytesNoCopy:buffer
length:j freeWhenDone:YES];
It really works!
As #runeb said the answer is not working properly with large files. You should do something like that:
int bufferSize = 2048;
int offset = 0;
NSString* name=nil;
while(offset<asset.size){
Byte *buffer = (Byte*)malloc(bufferSize);
NSUInteger buffered = [asset getBytes:buffer fromOffset:offset length:bufferSize error:nil];
NSData *data;
data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:NO];
if(!name){
//Creates the file and gives it a unique name
name = [FileUtils saveVideoFromAsset:data];
}
else{
//Append data to the file created...
[FileUtils appendData:data toFile:name];
}
offset+=buffered;
free(buffer);
}
In order to append data to a file you can use that:
NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
[myHandle seekToEndOfFile];
[myHandle writeData:videoData];
I hope that helps!
ust add #autoreleasepool block, so that any autorleased objects should be cleaned up. it looks like that ARC has something changed after iOS7
#autoreleasepool {
NSUInteger readStatus = [rep getBytes:buffer fromOffset:_startFromByte length:chunkSize error:NULL];
}

Resources