Skip to content

Commit 13e7513

Browse files
ptoffy0xTim
andauthored
[V4] Fix memory bug when loading keys (#208)
Fix leaking pointer Co-authored-by: Tim Condon <[email protected]>
1 parent 20ef179 commit 13e7513

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

Sources/JWTKit/Utilities/OpenSSLSigner.swift

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import Foundation
21
@_implementationOnly import CJWTKitBoringSSL
2+
import Foundation
33

44
protocol OpenSSLSigner {
55
var algorithm: OpaquePointer { get }
@@ -33,23 +33,25 @@ extension OpenSSLSigner {
3333
guard CJWTKitBoringSSL_EVP_DigestFinal_ex(context, &digest, &digestLength) == 1 else {
3434
throw JWTError.signingAlgorithmFailure(OpenSSLError.digestFinalizationFailure)
3535
}
36-
return .init(digest[0..<Int(digestLength)])
36+
return .init(digest[0 ..< Int(digestLength)])
3737
}
3838
}
3939

40-
protocol OpenSSLKey { }
40+
protocol OpenSSLKey {}
4141

4242
extension OpenSSLKey {
4343
static func load<Data, T>(pem data: Data, _ closure: (UnsafeMutablePointer<BIO>) -> (T?)) throws -> T
4444
where Data: DataProtocol
4545
{
46-
let bytes = data.copyBytes()
47-
let bio = CJWTKitBoringSSL_BIO_new_mem_buf(bytes, numericCast(bytes.count))
48-
defer { CJWTKitBoringSSL_BIO_free(bio) }
49-
50-
guard let bioPtr = bio, let c = closure(bioPtr) else {
51-
throw JWTError.signingAlgorithmFailure(OpenSSLError.bioConversionFailure)
46+
try data.copyBytes().withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
47+
let bio = CJWTKitBoringSSL_BIO_new_mem_buf(bytes.baseAddress, numericCast(bytes.count))
48+
49+
defer { CJWTKitBoringSSL_BIO_free(bio) }
50+
51+
guard let bioPtr = bio, let c = closure(bioPtr) else {
52+
throw JWTError.signingAlgorithmFailure(OpenSSLError.bioConversionFailure)
53+
}
54+
return c
5255
}
53-
return c
5456
}
5557
}

0 commit comments

Comments
 (0)