diff --git a/Sodium/GenericHash.swift b/Sodium/GenericHash.swift index 70d94be..3671b95 100644 --- a/Sodium/GenericHash.swift +++ b/Sodium/GenericHash.swift @@ -142,17 +142,23 @@ public class GenericHash { result = crypto_generichash_init(state, nil, 0, outputLength) } if result != 0 { + free() return nil } self.outputLength = outputLength } - deinit { + private func free() { guard let state = state else { return } let rawState = UnsafeMutableRawPointer(state).bindMemory(to: UInt8.self, capacity: crypto_generichash_statebytes()) rawState.deallocate(capacity: 1) + self.state = nil + } + + deinit { + free() } /** diff --git a/Sodium/SecretStream.swift b/Sodium/SecretStream.swift index 68e9ac9..d41ec58 100644 --- a/Sodium/SecretStream.swift +++ b/Sodium/SecretStream.swift @@ -80,6 +80,7 @@ public class SecretStream { } } if result != 0 { + free() return nil } } @@ -126,12 +127,17 @@ public class SecretStream { crypto_secretstream_xchacha20poly1305_rekey(state) } - deinit { + private func free() { guard let state = state else { return } let rawState = UnsafeMutableRawPointer(state).bindMemory(to: UInt8.self, capacity: crypto_secretstream_xchacha20poly1305_statebytes()) rawState.deallocate(capacity: 1) + self.state = nil + } + + deinit { + free() } } @@ -153,6 +159,7 @@ public class SecretStream { } } if result != 0 { + free() return nil } } @@ -195,12 +202,17 @@ public class SecretStream { crypto_secretstream_xchacha20poly1305_rekey(state) } - deinit { + private func free() { guard let state = state else { return } let rawState = UnsafeMutableRawPointer(state).bindMemory(to: UInt8.self, capacity: crypto_secretstream_xchacha20poly1305_statebytes()) rawState.deallocate(capacity: 1) + self.state = nil + } + + deinit { + free() } } }