I really need some help to convert the objective-c code to swift using CryptoSwift
. I'm not sure how to use functions like: bzero
, getCString
, malloc
in Swift.
+(NSData*)encryptData:(NSData*)data
{
static NSString *key = @"BitCave012345678";
char keyPtr[kCCKeySizeAES128+1];
bzero(keyPtr, sizeof(keyPtr));
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [data length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
keyPtr,kCCKeySizeAES128,NULL,[data bytes],dataLength,
buffer, bufferSize, &numBytesEncrypted);
if(cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer);
return nil;
}
Does anyone has an idea how to satisfy arguments requiring pointers?
I was trying using UnsafeMutablePointers
and I also tried the code below, but I know it is completely wrong:
var key: NSString = "BitCave012345678"
var keyPtr: Array<Character> = Array<Character>(count: 17, repeatedValue: "0")
bzero(&keyPtr, 17*sizeof(Character))
key.getCString(&keyPtr, maxLength: 17*sizeof(Character), encoding: NSUTF8StringEncoding)
Swift 2.0
It is not necessary to use bzero, getCString, malloc, here is an example that does not:
Add Security.framework to the project
Add #import to the bridging header.
Example usage:
Here is version in Swift
Arrays
of UInt8 with noNSData
objects:Example usage: