From 4e7f2edab817c40019fc3e43f44fb9ea83323fe1 Mon Sep 17 00:00:00 2001 From: RockfordWei Date: Wed, 17 Jan 2018 12:05:41 -0500 Subject: [PATCH] Improving password storage security by adding salt. --- .../Schema/Account.swift | 45 +++++++++---------- 1 file changed, 21 insertions(+), 24 deletions(-) diff --git a/Sources/PerfectLocalAuthentication/Schema/Account.swift b/Sources/PerfectLocalAuthentication/Schema/Account.swift index 2772949..ecb2b00 100644 --- a/Sources/PerfectLocalAuthentication/Schema/Account.swift +++ b/Sources/PerfectLocalAuthentication/Schema/Account.swift @@ -10,11 +10,13 @@ import StORM import MySQLStORM import SwiftRandom import PerfectSMTP +import PerfectCrypto public class Account: MySQLStORM { public var id = "" public var username = "" public var password = "" + public var salt = "" public var email = "" public var usertype: AccountType = .provisional public var source = "local" // local, facebook, etc @@ -109,11 +111,12 @@ public class Account: MySQLStORM { } public func makePassword(_ p1: String) { - if let digestBytes = p1.digest(.sha256), - let hexBytes = digestBytes.encode(.hex), - let hexBytesStr = String(validatingUTF8: hexBytes) { - password = hexBytesStr - } + if let random = ([UInt8](randomCount: 16)).encode(.hex), + let salt = String(validatingUTF8: random), + let shadow = p1.encrypt(.aes_128_cbc, password: p1, salt: salt) { + password = shadow + self.salt = salt + } } public func isUnique() throws { @@ -186,25 +189,19 @@ public class Account: MySQLStORM { // Login User public static func login(_ u: String, _ p: String) throws -> Account { - if let digestBytes = p.digest(.sha256), - let hexBytes = digestBytes.encode(.hex), - let hexBytesStr = String(validatingUTF8: hexBytes) { - - let acc = Account() - let criteria = ["username":u,"password":hexBytesStr] - do { - try acc.find(criteria) - if acc.usertype == .provisional { - throw OAuth2ServerError.loginError - } - return acc - } catch { - print(error) - throw OAuth2ServerError.loginError - } - } else { - throw OAuth2ServerError.loginError - } + let acc = Account() + let criteria = ["username":u] + do { + try acc.find(criteria) + guard let pwd = acc.password.decrypt(.aes_128_cbc, password: p, salt: acc.salt), + pwd == p, acc.usertype != .provisional else { + throw OAuth2ServerError.loginError + } + return acc + } catch { + print(error) + throw OAuth2ServerError.loginError + } } public static func listUsers() -> [[String: Any]] {