+ (NSData *)secretBoxOpen:(NSData *)data key:(SecureData *)key {
if (!data || [data length] < crypto_secretbox_noncebytes() || !key || [key length] != crypto_secretbox_keybytes())
return nil;
// Split it into nonce and encrypted data
NSData *nonce = [NSData dataWithBytes:[data bytes] length:crypto_secretbox_noncebytes()];
NSData *encryptedData = [NSData dataWithBytes:([data bytes] + crypto_secretbox_noncebytes()) length:[data length] - crypto_secretbox_noncebytes()];
// First BOXZEROBYTES must be 0
NSMutableData *encryptedPaddedData = [NSMutableData dataWithLength:crypto_secretbox_boxzerobytes()];
[encryptedPaddedData appendData:encryptedData];
NSMutableData *outData = [NSMutableData dataWithLength:[encryptedPaddedData length]];
int retval = crypto_secretbox_open([outData mutableBytes],
[encryptedPaddedData bytes], [encryptedPaddedData length],
[nonce bytes], [key bytes]);
if (retval != 0) return nil;
// Remove ZEROBYTES from out data
return [NSData dataWithBytes:([outData bytes] + crypto_secretbox_zerobytes())
length:([outData length] - crypto_secretbox_zerobytes())];
}
You'll notice in RbNaCL library open method here:
https://github.com/cryptosphere/rbnacl/blob/master/lib/rbnacl/secret_boxes/xsalsa20poly1305.rb
as required in docs at http://nacl.cr.yp.to/secretbox.html
Here is the other side:
+ (NSData *)secretBox:(NSData *)data key:(SecureData *)key {
NSData *nonce = [Random randomData:crypto_secretbox_noncebytes()];
if (!data || !key || [key length] != crypto_secretbox_keybytes() || !nonce || [nonce length] != crypto_secretbox_noncebytes())
return nil;
// Pad the datas by ZEROBYTES
NSMutableData *paddedData = [NSMutableData dataWithLength:crypto_secretbox_zerobytes()];
[paddedData appendData:data];
NSMutableData *outData = [NSMutableData dataWithLength:[paddedData length]];
int retval = crypto_secretbox([outData mutableBytes],
[paddedData bytes], [paddedData length],
[nonce bytes],
[key bytes]);
if (retval != 0) return nil;
// Remove BOXZEROBYTES from out data
outData = [NSData dataWithBytes:([outData bytes] + crypto_secretbox_boxzerobytes())
length:([outData length] - crypto_secretbox_boxzerobytes())];
NSMutableData *combined = [NSMutableData dataWithData:nonce];
[combined appendData:outData];
return combined;
}
You'll notice in RbNaCL library open method here:
https://github.com/cryptosphere/rbnacl/blob/master/lib/rbnacl/secret_boxes/xsalsa20poly1305.rb
as required in docs at http://nacl.cr.yp.to/secretbox.html
Here is the other side: