Merge pull request #13943 from geoffw0/weakhashexample

Swift: Update the weak sensitive data hashing examples and qhelp
This commit is contained in:
Geoffrey White
2023-08-30 10:36:23 +01:00
committed by GitHub
3 changed files with 28 additions and 10 deletions

View File

@@ -51,18 +51,25 @@
</li>
</ul>
<p>
Note that special purpose algorithms, which are used to ensure that a message comes from a particular sender, exist for message authentication. These algorithms should be used when appropriate, as they address common vulnerabilities of simple hashing schemes in this context.
</p>
</recommendation>
<example>
<p>
The following examples show a function for checking whether the hash
of a certificate matches a known value -- to prevent tampering.
The following examples show a function for fetching data from a
URL along with a hash of the data, perhaps to check the data has
not been tampered with.
</p>
<p>
In the first case the MD5 hashing algorithm is used that is known to be vulnerable to collision attacks.
</p>
<sample src="WeakSensitiveDataHashingBad.swift"/>
<p>
<p>
Here is the same function using SHA-512, which is a strong cryptographic hashing function.
</p>
<sample src="WeakSensitiveDataHashingGood.swift"/>

View File

@@ -1,5 +1,10 @@
typealias Hasher = Crypto.Insecure.MD5
func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool
return Hasher.hash(data: cert) == hash // BAD
func getContentsAndHash(url: URL) -> (Data, String)? {
guard let data = try? Data(contentsOf: url) else {
return nil
}
let digest = Insecure.MD5.hash(data: data)
let hash = digest.map { String(format: "%02hhx", $0) }.joined()
return (data, hash)
}

View File

@@ -1,4 +1,10 @@
typealias Hasher = Crypto.SHA512
func getContentsAndHash(url: URL) -> (Data, String)? {
guard let data = try? Data(contentsOf: url) else {
return nil
}
func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool
return Hasher.hash(data: cert) == hash // GOOD
let digest = SHA512.hash(data: data)
let hash = digest.map { String(format: "%02hhx", $0) }.joined()
return (data, hash)
}