Implemented hashing login password with scrypt (but still using a static salt; CryptoSwift has accidentally already been commit with last commit)

This commit is contained in:
dankito 2020-10-14 02:16:26 +02:00
parent acf0345aaf
commit b1c027b608
1 changed files with 47 additions and 23 deletions

View File

@ -1,5 +1,6 @@
import SwiftUI
import LocalAuthentication
import CryptoSwift
import BankingUiSwift
@ -95,14 +96,19 @@ class AuthenticationService {
}
func authenticateUserWithPassword(_ enteredPassword: String, _ authenticationResult: @escaping (Bool, String?) -> Void) {
if retrieveLoginPassword() == enteredPassword {
if let storedHash = readLoginPasswordHash() {
if let hashOfEnteredPassword = hashLoginPassword(enteredPassword) {
if storedHash == hashOfEnteredPassword {
let decryptDatabaseResult = openDatabase(false, enteredPassword)
authenticationResult(decryptDatabaseResult, nil)
return
}
else {
}
}
authenticationResult(false, "Incorrect password entered".localize())
}
}
@discardableResult
private func openDatabase(_ useBiometricAuthentication: Bool, _ userLoginPassword: String?) -> Bool {
@ -291,11 +297,13 @@ class AuthenticationService {
@discardableResult
private func setLoginPassword(_ newPassword: String) -> Bool {
do {
if let passwordHash = hashLoginPassword(newPassword) {
let passwordItem = createUserLoginPasswordKeychainItem()
try passwordItem.savePassword(newPassword)
try passwordItem.savePassword(passwordHash)
return true
}
} catch {
NSLog("Could not save login password: \(error)")
}
@ -303,6 +311,18 @@ class AuthenticationService {
return false
}
private func readLoginPasswordHash() -> String? {
do {
let passwordItem = createUserLoginPasswordKeychainItem()
return try passwordItem.readPassword()
} catch {
NSLog("Could not read login password: \(error)")
}
return nil
}
@discardableResult
private func deleteLoginPassword() -> Bool {
do {
@ -318,18 +338,6 @@ class AuthenticationService {
return false
}
private func retrieveLoginPassword() -> String? {
do {
let passwordItem = createUserLoginPasswordKeychainItem()
return try passwordItem.readPassword()
} catch {
NSLog("Could not read login password: \(error)")
}
return nil
}
private func createUserLoginPasswordKeychainItem() -> KeychainPasswordItem {
return KeychainPasswordItem(Self.UserLoginPasswordKeychainAccountName)
}
@ -352,6 +360,22 @@ class AuthenticationService {
}
private func hashLoginPassword(_ loginPassword: String) -> String? {
do {
let password = Array(loginPassword.utf8)
//let salt = Array(generateRandomPassword(8).utf8)
let salt = Array("aaaaaaaa".utf8)
let bytes = try Scrypt(password: password, salt: salt, dkLen: 64, N: 256, r: 8, p: 1).calculate()
return bytes.toBase64()
} catch {
NSLog("Could not create hash for login password: \(error)")
}
return nil
}
private func concatPasswords(_ loginPassword: String, _ defaultPassword: String) -> String {
return loginPassword + "_" + defaultPassword
}