SecKeyEncrypt returns error -50 and 0 cipherSize - swift

I am porting a PKI api to Swift 2.2 and found the following error. Everything works fine in Objective-C.
The data object to be encrypted is 32 bytes in size. This is the code I am using.
let buflen = 64
var cipherBuffer = UnsafeMutablePointer<UInt8>.alloc(buflen)
cipherBuffer[buflen] = 0 // zero terminate
var cipherLength: Int = 0
var statusCode: OSStatus?
let dataPointer = UnsafePointer<UInt8>(data.bytes)
statusCode = SecKeyEncrypt(publicKey, SecPadding.PKCS1, dataPointer, data.length, cipherBuffer, &cipherLength)
This results in an error -50 and 0 cipher length.
I am doing an hexdump of the public key and the dataPointer to ensure they are OK, but can´t find the problem with the SecKeyEncrypt call
Any help will be appreciated

After some research I found a solution to the problem
I was creating the cipherBuffer using alloc and zero terminating the array, as follows:
let buflen = 64
var cipherBuffer = UnsafeMutablePointer<UInt8>.alloc(buflen)
cipherBuffer[buflen] = 0 // zero terminate
I tried the following approach and it works fine.
let blockSize = SecKeyGetBlockSize(publicKey) //64
var cipherBuffer = [UInt8](count: Int(blockSize), repeatedValue: 0)
Given that both approaches reported a block of 64 bytes with 0x00 using hexDump, I did a quick test and reviewed the previous code and found that removing the line with "cipherBuffer[buflen] = 0" fixes the problem.
It seems that it has to do with the zero termination of the array, or I may have done something weird.

Related

iOS13 SceneKit Error – Purging never freed texture

I have an ARKit app that runs fine on iOS 12.x. On iOS 13 I encounter the following error in the console log:
[SceneKit] Error: Purging never freed texture <AGXA9FamilyTexture: 0x11d688240>
label = <none>
textureType = MTLTextureType2D
pixelFormat = MTLPixelFormatR16Float
width = 240
height = 1
depth = 1
arrayLength = 1
mipmapLevelCount = 1
sampleCount = 1
cpuCacheMode = MTLCPUCacheModeDefaultCache
storageMode = MTLStorageModePrivate
hazardTrackingMode = MTLHazardTrackingModeTracked
resourceOptions = MTLResourceCPUCacheModeDefaultCache MTLResourceStorageModePrivate MTLResourceHazardTrackingModeTracked
usage = MTLTextureUsageShaderRead MTLTextureUsageShaderWrite
shareable = 0
framebufferOnly = 0
purgeableState = MTLPurgeableStateNonVolatile
swizzle = [MTLTextureSwizzleRed, MTLTextureSwizzleGreen, MTLTextureSwizzleBlue, MTLTextureSwizzleAlpha]
isCompressed = 0
parentTexture = <null>
parentRelativeLevel = 0
parentRelativeSlice = 0
buffer = <null>
bufferOffset = 512
bufferBytesPerRow = 0
allowGPUOptimizedContents = YES
label = <none>
It repeats every few milliseconds and clutters the whole log. I was not able to narrow down where it comes from.
The interesting part is, that this even occurs when not a single node is present in the scene. If I remove the entire sceneView from the view then it disappears...(not an option)
Anybody any idea or hint how to track this down ?
Thanks
I fixed this issue by updating the setting of the scene camera:
var sceneView: ARSCNView!
...
sceneView.pointOfView?.camera?.wantsHDR = false
Hope this helps.
I have found the problem code line. In iOS 13 any call to
SceneView.snapshot()
produces that error. The apple docs say:
This method is thread-safe and may be called at any time.
but this seems to have changed in iOS13. I will file a bug report not hoping for a fast solution ;-)

How to use sizeof() method in Swift 4

I am trying to implement this code which I got from an apple WWDC video. However the video is from 2016 and I think the syntax has changed. How do I call sizeof(Float)? This produces an error.
func render(buffer:AudioBuffer){
let nFrames = Int(buffer.mDataByteSize) / sizeof(Float)
var ptr = UnsafeMutableRawPointer(buffer.mData)
var j = self.counter
let cycleLength = self.sampleRate / self.frequency
let halfCycleLength = cycleLength / 2
let amp = self.amplitude, minusAmp = -amp
for _ in 0..<nFrames{
if j < halfCycleLength{
ptr.pointee = amp
} else {
ptr.pointee = minusAmp
}
ptr = ptr.successor()
j += 1.0
if j > cycleLength {
}
}
self.counter = j
}
The sizeof() function is no longer supported in Swift.
As Leo Dabus said in his comment, you want MemoryLayout<Type>.size, or in your case, MemoryLayout<Float>.size.
Note that tells you the abstract size of an item of that type. However, due to alignment, you should not assume that structs containing different types of items will be the sums of the sizes of the other elements. Also, you need to consider the device it's running on. On a 64 bit device, Int is 8 bytes. On a 32 bit device, it's 4 bytes.
See the article on MemoryLayout at SwiftDoc.org for more information.

How to convert int from an NSimage to JPEG in swift OS Xcode 7.3.1

I extra data from an image and save as int data. I want to convert back to an JPEG image. Thank You.
for j in 1 ..< dataCount!-1 {
var z = ImageArray![j]
if ( z > 0 ){
data[j] =z
}
else if (z < 0){
var y = 256 + z
data[j] = y
}
i += 1
}
*** need to convert int to byte ****** but don't know how to do that.
byteArray.writeToFile("/Users/picpath/picture.jpg", atomically: true )
to convert image into bytes you can use the following line of code.
var nsdata = UIImageJPEGRepresentation(data[j], 1)
The function takes two parameters , first parameter should be an image and the second parameter which is a float is used to define the compression ratio. by default we use "1"
This will convert image into bytes. Hopefully this will help you
Cheers

Really fast addition of Strings in swift

The code below shows two ways of building a spreadsheet :
by using:
str = str + "\(number) ; "
or
str.append("\(number)");
Both are really slow because, I think, they discard both strings and make a third one which is the concatenation of the first two.
Now, If I repeat this operation hundreds of thousands of times to grow a spreadsheet... that makes a lot of allocations.
For instance, the code below takes 11 seconds to execute on my MacBook Pro 2016:
let start = Date()
var str = "";
for i in 0 ..< 86400
{
for j in 0 ..< 80
{
// Use either one, no difference
// str = str + "\(Double(j) * 1.23456789086756 + Double(i)) ; "
str.append("\(Double(j) * 1.23456789086756 + Double(i)) ; ");
}
str.append("\n")
}
let duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration);
How can I solve this issue without having to convert the doubles to string myself ? I have been stuck on this for 3 days... my programming skills are pretty limited, as you can probably see from the code above...
I tried:
var str = NSMutableString(capacity: 86400*80*20);
but the compiler tells me:
Variable 'str' was never mutated; consider changing to 'let' constant
despite the
str.append("\(Double(j) * 1.23456789086756 + Double(i)) ; ");
So apparently, calling append does not mutate the string...
I tried writing it to an array and the limiting factor seems to be the conversion of a double to a string.
The code below takes 13 seconds or so on my air
doing this
arr[i][j] = "1.23456789086756"
drops the execution time to 2 seconds so 11 seconds is taken up in converting Double to String. You might be able to shave off some time by writing your own conversion routine but that seems the limiting factor. I tried using memory streams and that seems even slower.
var start = Date()
var arr = Array(repeating: Array(repeating: "1.23456789086756", count: 80), count: 86400 )
var duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration); //0.007
start = Date()
var a = 1.23456789086756
for i in 0 ..< 86400
{
for j in 0 ..< 80
{
arr[i][j] = "\(a)" // "1.23456789086756" //String(a)
}
}
duration = Date().timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate;
print(duration); //13.46 or 2.3 with the string

Amount of data to be sent to peripheral using bluetooth in ios 8

I am working in data transferring using bluetooth from BLE device to peripheral hardware. I want to write data from binary file in chunks as total data length is 143233. I found one line "Maximal MTU was 132 bytes for iOS 7 devices and 20 B for iOS 6" but what about iOS 8?
What will be maximum size of chunks for iOS 8? This is the code which I have used, I dont know whether i am going right way or not so help me and guide me if i am going wrong. Thanks in advance.
var count:Int = 0
var counter:Int = 0
var str:NSString = NSBundle.mainBundle().pathForResource("spp", ofType: "bin")!
println("string value is \(str)")
var dataFile:NSString = NSString.stringWithContentsOfFile(str, encoding: NSASCIIStringEncoding, error: nil)
data = dataFile.dataUsingEncoding(NSUTF8StringEncoding)
println(data!.length)
println(dataFile.length)
var dataLen:Int = data!.length
if (dataLen > 132)
{
while(count < dataLen && dataLen - count > 132)
{
peripheral.writeValue(data!.subdataWithRange(NSMakeRange(count, 132)), forCharacteristic: arrCharacteristics!.objectAtIndex(1) as CBCharacteristic , type: CBCharacteristicWriteType.WithResponse)
NSThread.sleepForTimeInterval(0.005)
println("Write performed \(counter++ )")
count += 132
}
} if (count < dataLen)
{
peripheral.writeValue(data!.subdataWithRange(NSMakeRange(count, dataLen - count)), forCharacteristic: arrCharacteristics!.objectAtIndex(1) as CBCharacteristic , type: CBCharacteristicWriteType.WithResponse)
}
I'm guessing Jalek found his answer but for anyone else seeking the figures.
iOS 7 requests a 135 byte MTU (132 bytes data + 3 overhead).
iOS 8 requests a 158 byte MTU (155 bytes data + 3 overhead).
Obviously, it will depend on the other device whether these values are accepted or a lower value returned.