Skip to content

Commit

Permalink
Factor out withNewBignumContext helper
Browse files Browse the repository at this point in the history
  • Loading branch information
simonjbeaumont committed May 31, 2024
1 parent 56d0253 commit 60f26f0
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions Sources/_CryptoExtras/Util/BoringSSLHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,10 @@ extension BIGNUM {
withUnsafePointer(to: self) { selfPtr in
withUnsafePointer(to: rhs) { rhsPtr in
if let modulus {
let bnCtx = CCryptoBoringSSL_BN_CTX_new()!
defer { CCryptoBoringSSL_BN_CTX_free(bnCtx) }
return withUnsafePointer(to: modulus) { modulusPtr in
CCryptoBoringSSL_BN_mod_sub(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtx)
withNewBignumContext { bnCtxPtr in
CCryptoBoringSSL_BN_mod_sub(resultPtr, selfPtr, rhsPtr, modulusPtr, bnCtxPtr)
}
}
} else {
return CCryptoBoringSSL_BN_sub(resultPtr, selfPtr, rhsPtr)
Expand All @@ -142,12 +142,12 @@ extension BIGNUM {
let rc = withUnsafeMutablePointer(to: &result) { resultPtr in
withUnsafePointer(to: self) { selfPtr in
withUnsafePointer(to: mod) { modPtr in
let bnCtx = CCryptoBoringSSL_BN_CTX_new()!
defer { CCryptoBoringSSL_BN_CTX_free(bnCtx) }
if nonNegative {
return CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtx)
} else {
return CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtx)
withNewBignumContext { bnCtxPtr in
if nonNegative {
return CCryptoBoringSSL_BN_nnmod(resultPtr, selfPtr, modPtr, bnCtxPtr)
} else {
return CCryptoBoringSSLShims_BN_mod(resultPtr, selfPtr, modPtr, bnCtxPtr)
}
}
}
}
Expand All @@ -163,16 +163,23 @@ extension BIGNUM {
let rc = withUnsafeMutablePointer(to: &result) { resultPtr in
withUnsafePointer(to: self) { selfPtr in
withUnsafePointer(to: mod) { modPtr in
let bnCtx = CCryptoBoringSSL_BN_CTX_new()!
defer { CCryptoBoringSSL_BN_CTX_free(bnCtx) }
return CCryptoBoringSSL_BN_mod_inverse(resultPtr, selfPtr, modPtr, bnCtx)
withNewBignumContext { bnCtxPtr in
CCryptoBoringSSL_BN_mod_inverse(resultPtr, selfPtr, modPtr, bnCtxPtr)
}
}
}
}
precondition(rc != nil, "Unable to allocate memory for new BIGNUM")

return result
}

}

fileprivate func withNewBignumContext<R>(_ body: (OpaquePointer /* BN_CTX* */) throws -> R) rethrows -> R {
let bnCtxPtr = CCryptoBoringSSL_BN_CTX_new()!
defer { CCryptoBoringSSL_BN_CTX_free(bnCtxPtr) }
return try body(bnCtxPtr)
}

extension _RSA.BlindSigning.PublicKey {
Expand Down

0 comments on commit 60f26f0

Please sign in to comment.