Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swift 3 function names #80

Merged
merged 8 commits into from
Nov 16, 2016
2 changes: 1 addition & 1 deletion Sources/Crypto.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import Foundation
import CommonCrypto

func HMAC(_ algorithm: Generator.Algorithm, key: Data, data: Data) -> Data {
func HMAC(algorithm: Generator.Algorithm, key: Data, data: Data) -> Data {
let (hashFunction, hashLength) = algorithm.hashInfo

let macOut = UnsafeMutablePointer<UInt8>.allocate(capacity: hashLength)
Expand Down
12 changes: 6 additions & 6 deletions Sources/Generator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,18 @@ public struct Generator: Equatable {
///
/// - throws: A `Generator.Error` if a valid password cannot be generated for the given time.
/// - returns: The generated password, or throws an error if a password could not be generated.
public func passwordAtTime(_ time: TimeInterval) throws -> String {
public func password(at time: TimeInterval) throws -> String {
guard Generator.validateDigits(digits) else {
throw Error.invalidDigits
}

let counter = try factor.counterAtTime(time)
let counter = try factor.counterValue(at: time)
// Ensure the counter value is big-endian
var bigCounter = counter.bigEndian

// Generate an HMAC value from the key and counter
let counterData = Data(bytes: &bigCounter, count: MemoryLayout<UInt64>.size)
let hash = HMAC(algorithm, key: secret, data: counterData)
let hash = HMAC(algorithm: algorithm, key: secret, data: counterData)

var truncatedHash = hash.withUnsafeBytes { (ptr: UnsafePointer<UInt8>) -> UInt32 in
// Use the last 4 bits of the hash as an offset (0 <= offset <= 15)
Expand All @@ -99,7 +99,7 @@ public struct Generator: Equatable {
truncatedHash = truncatedHash % UInt32(pow(10, Float(digits)))

// Pad the string representation with zeros, if necessary
return String(truncatedHash).paddedWithCharacter("0", toLength: digits)
return String(truncatedHash).padded(with: "0", toLength: digits)
}

// MARK: Update
Expand Down Expand Up @@ -149,7 +149,7 @@ public struct Generator: Equatable {
///
/// - throws: A `Generator.Error` if a valid counter cannot be calculated.
/// - returns: The counter value needed to generate the password for the target time.
fileprivate func counterAtTime(_ time: TimeInterval) throws -> UInt64 {
fileprivate func counterValue(at time: TimeInterval) throws -> UInt64 {
switch self {
case .counter(let counter):
return counter
Expand Down Expand Up @@ -247,7 +247,7 @@ private extension String {
/// - parameter length: The desired length of the padded string.
///
/// - returns: A new string padded to the given length.
func paddedWithCharacter(_ character: Character, toLength length: Int) -> String {
func padded(with character: Character, toLength length: Int) -> String {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid Docs Violation: Documented declarations should be valid. (valid_docs)

let paddingCount = length - characters.count
guard paddingCount > 0 else { return self }

Expand Down
26 changes: 12 additions & 14 deletions Sources/Keychain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public final class Keychain {
///
/// - throws: A `Keychain.Error` if an error occurred.
/// - returns: The persistent token, or `nil` if no token matched the given identifier.
public func persistentTokenWithIdentifier(_ identifier: Data) throws -> PersistentToken? {
return try keychainItemForPersistentRef(identifier).flatMap(PersistentToken.init)
public func persistentToken(withIdentifier identifier: Data) throws -> PersistentToken? {
return try keychainItem(forPersistentRef: identifier).flatMap(PersistentToken.init)
}

/// Returns the set of all persistent tokens found in the keychain.
Expand All @@ -58,9 +58,9 @@ public final class Keychain {
///
/// - throws: A `Keychain.Error` if the token was not added successfully.
/// - returns: The new persistent token.
public func addToken(_ token: Token) throws -> PersistentToken {
public func add(_ token: Token) throws -> PersistentToken {
let attributes = try token.keychainAttributes()
let persistentRef = try addKeychainItemWithAttributes(attributes)
let persistentRef = try addKeychainItem(withAttributes: attributes)
return PersistentToken(token: token, identifier: persistentRef)
}

Expand All @@ -71,11 +71,9 @@ public final class Keychain {
///
/// - throws: A `Keychain.Error` if the update did not succeed.
/// - returns: The updated persistent token.
public func updatePersistentToken(_ persistentToken: PersistentToken,
withToken token: Token) throws -> PersistentToken
{
public func update(_ persistentToken: PersistentToken, with token: Token) throws -> PersistentToken {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line Length Violation: Line should be 100 characters or less: currently 105 characters (line_length)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Barely over the limit, and definitely more readable on one line.

let attributes = try token.keychainAttributes()
try updateKeychainItemForPersistentRef(persistentToken.identifier,
try updateKeychainItem(forPersistentRef: persistentToken.identifier,
withAttributes: attributes)
return PersistentToken(token: token, identifier: persistentToken.identifier)
}
Expand All @@ -88,8 +86,8 @@ public final class Keychain {
/// - parameter persistentToken: The persistent token to delete.
///
/// - throws: A `Keychain.Error` if the deletion did not succeed.
public func deletePersistentToken(_ persistentToken: PersistentToken) throws {
try deleteKeychainItemForPersistentRef(persistentToken.identifier)
public func delete(_ persistentToken: PersistentToken) throws {
try deleteKeychainItem(forPersistentRef: persistentToken.identifier)
}

// MARK: Errors
Expand Down Expand Up @@ -139,7 +137,7 @@ private extension PersistentToken {
}
}

private func addKeychainItemWithAttributes(_ attributes: [String: AnyObject]) throws -> Data {
private func addKeychainItem(withAttributes attributes: [String: AnyObject]) throws -> Data {
var mutableAttributes = attributes
mutableAttributes[kSecClass as String] = kSecClassGenericPassword
mutableAttributes[kSecReturnPersistentRef as String] = kCFBooleanTrue
Expand All @@ -163,7 +161,7 @@ private func addKeychainItemWithAttributes(_ attributes: [String: AnyObject]) th
return persistentRef
}

private func updateKeychainItemForPersistentRef(_ persistentRef: Data,
private func updateKeychainItem(forPersistentRef persistentRef: Data,
withAttributes attributesToUpdate: [String: AnyObject]) throws
{
let queryDict: [String : AnyObject] = [
Expand All @@ -178,7 +176,7 @@ private func updateKeychainItemForPersistentRef(_ persistentRef: Data,
}
}

private func deleteKeychainItemForPersistentRef(_ persistentRef: Data) throws {
private func deleteKeychainItem(forPersistentRef persistentRef: Data) throws {
let queryDict: [String : AnyObject] = [
kSecClass as String: kSecClassGenericPassword,
kSecValuePersistentRef as String: persistentRef as NSData,
Expand All @@ -191,7 +189,7 @@ private func deleteKeychainItemForPersistentRef(_ persistentRef: Data) throws {
}
}

private func keychainItemForPersistentRef(_ persistentRef: Data) throws -> NSDictionary? {
private func keychainItem(forPersistentRef persistentRef: Data) throws -> NSDictionary? {
let queryDict: [String : AnyObject] = [
kSecClass as String: kSecClassGenericPassword,
kSecValuePersistentRef as String: persistentRef as NSData,
Expand Down
4 changes: 2 additions & 2 deletions Sources/Token+URL.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ extension Token {

/// Attempts to initialize a token represented by the give URL.
public init?(url: URL, secret: Data? = nil) {
if let token = tokenFromURL(url, secret: secret) {
if let token = token(from: url, secret: secret) {
self = token
} else {
return nil
Expand Down Expand Up @@ -117,7 +117,7 @@ private func urlForToken(name: String, issuer: String, factor: Generator.Factor,
return url
}

private func tokenFromURL(_ url: URL, secret externalSecret: Data? = nil) -> Token? {
private func token(from url: URL, secret externalSecret: Data? = nil) -> Token? {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Body Length Violation: Function body should span 40 lines or less excluding comments and whitespace: currently spans 46 lines (function_body_length)
Cyclomatic Complexity Violation: Function should have complexity 10 or less: currently complexity equals 13 (cyclomatic_complexity)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ignoring these warnings, as the represent issues that already exist and aren't being exacerbated by this PR.

guard url.scheme == kOTPAuthScheme else {
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/Token.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public struct Token: Equatable {
/// - returns: The current password, or `nil` if a password could not be generated.
public var currentPassword: String? {
let currentTime = Date().timeIntervalSince1970
return try? generator.passwordAtTime(currentTime)
return try? generator.password(at: currentTime)
}

// MARK: Update
Expand Down
16 changes: 8 additions & 8 deletions Tests/GeneratorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ class GeneratorTests: XCTestCase {
let counter = Generator.Factor.counter(count)
let secret = "12345678901234567890".data(using: String.Encoding.ascii)!
let hotp = Generator(factor: counter, secret: secret, algorithm: .SHA1, digits: 6)
.flatMap { try? $0.passwordAtTime(time) }
.flatMap { try? $0.password(at: time) }
let totp = Generator(factor: timer, secret: secret, algorithm: .SHA1, digits: 6)
.flatMap { try? $0.passwordAtTime(time) }
.flatMap { try? $0.password(at: time) }
XCTAssertEqual(hotp, totp,
"TOTP with \(timer) should match HOTP with counter \(counter) at time \(time).")
}
Expand Down Expand Up @@ -161,7 +161,7 @@ class GeneratorTests: XCTestCase {

let badTime: TimeInterval = -100
do {
_ = try generator.passwordAtTime(badTime)
_ = try generator.password(at: badTime)
} catch Generator.Error.invalidTime {
// This is the expected type of error
return
Expand All @@ -177,7 +177,7 @@ class GeneratorTests: XCTestCase {
let time: TimeInterval = 100

do {
_ = try generator.passwordAtTime(time)
_ = try generator.password(at: time)
} catch Generator.Error.invalidPeriod {
// This is the expected type of error
return
Expand All @@ -193,7 +193,7 @@ class GeneratorTests: XCTestCase {
let time: TimeInterval = 100

do {
_ = try generator.passwordAtTime(time)
_ = try generator.password(at: time)
} catch Generator.Error.invalidDigits {
// This is the expected type of error
return
Expand Down Expand Up @@ -222,7 +222,7 @@ class GeneratorTests: XCTestCase {
]
for (counter, expectedPassword) in expectedValues {
let generator = Generator(factor: .counter(counter), secret: secret, algorithm: .SHA1, digits: 6)
let password = generator.flatMap { try? $0.passwordAtTime(0) }
let password = generator.flatMap { try? $0.password(at: 0) }
XCTAssertEqual(password, expectedPassword,
"The generator did not produce the expected OTP.")
}
Expand Down Expand Up @@ -251,7 +251,7 @@ class GeneratorTests: XCTestCase {

for i in 0..<times.count {
let expectedPassword = expectedValues[algorithm]?[i]
let password = generator.flatMap { try? $0.passwordAtTime(times[i]) }
let password = generator.flatMap { try? $0.password(at: times[i]) }
XCTAssertEqual(password, expectedPassword,
"Incorrect result for \(algorithm) at \(times[i])")
}
Expand All @@ -274,7 +274,7 @@ class GeneratorTests: XCTestCase {
let generator = Generator(factor: .timer(period: 30), secret: secret, algorithm: algorithm, digits: 6)
for i in 0..<times.count {
let expectedPassword = expectedPasswords[i]
let password = generator.flatMap { try? $0.passwordAtTime(times[i]) }
let password = generator.flatMap { try? $0.password(at: times[i]) }
XCTAssertEqual(password, expectedPassword,
"Incorrect result for \(algorithm) at \(times[i])")
}
Expand Down
49 changes: 24 additions & 25 deletions Tests/KeychainTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ class KeychainTests: XCTestCase {
// Save the token
let savedToken: PersistentToken
do {
savedToken = try keychain.addToken(token)
savedToken = try keychain.add(token)
} catch {
XCTFail("addToken(_:) failed with error: \(error)")
return
}

// Restore the token
do {
let fetchedToken = try keychain.persistentTokenWithIdentifier(savedToken.identifier)
let fetchedToken = try keychain.persistentToken(withIdentifier: savedToken.identifier)
XCTAssertEqual(fetchedToken, savedToken, "Token should have been saved to keychain")
} catch {
XCTFail("persistentTokenWithIdentifier(_:) failed with error: \(error)")
Expand All @@ -77,8 +77,7 @@ class KeychainTests: XCTestCase {
generator: token.generator.successor()
)
do {
let updatedToken = try keychain.updatePersistentToken(savedToken,
withToken: modifiedToken)
let updatedToken = try keychain.update(savedToken, with: modifiedToken)
XCTAssertEqual(updatedToken.identifier, savedToken.identifier)
XCTAssertEqual(updatedToken.token, modifiedToken)
} catch {
Expand All @@ -87,7 +86,7 @@ class KeychainTests: XCTestCase {

// Fetch the token again
do {
let fetchedToken = try keychain.persistentTokenWithIdentifier(savedToken.identifier)
let fetchedToken = try keychain.persistentToken(withIdentifier: savedToken.identifier)
XCTAssertEqual(fetchedToken?.token, modifiedToken)
XCTAssertEqual(fetchedToken?.identifier, savedToken.identifier)
} catch {
Expand All @@ -96,14 +95,14 @@ class KeychainTests: XCTestCase {

// Remove the token
do {
try keychain.deletePersistentToken(savedToken)
try keychain.delete(savedToken)
} catch {
XCTFail("deletePersistentToken(_:) failed with error: \(error)")
}

// Attempt to restore the deleted token
do {
let fetchedToken = try keychain.persistentTokenWithIdentifier(savedToken.identifier)
let fetchedToken = try keychain.persistentToken(withIdentifier: savedToken.identifier)
XCTAssertNil(fetchedToken, "Token should have been removed from keychain")
} catch {
XCTFail("persistentTokenWithIdentifier(_:) failed with error: \(error)")
Expand All @@ -120,8 +119,8 @@ class KeychainTests: XCTestCase {
let savedItem1: PersistentToken
let savedItem2: PersistentToken
do {
savedItem1 = try keychain.addToken(token1)
savedItem2 = try keychain.addToken(token2)
savedItem1 = try keychain.add(token1)
savedItem2 = try keychain.add(token2)
XCTAssertEqual(savedItem1.token, token1)
XCTAssertEqual(savedItem2.token, token2)
} catch {
Expand All @@ -131,8 +130,8 @@ class KeychainTests: XCTestCase {

// Fetch both tokens from the keychain
do {
let fetchedItem1 = try keychain.persistentTokenWithIdentifier(savedItem1.identifier)
let fetchedItem2 = try keychain.persistentTokenWithIdentifier(savedItem2.identifier)
let fetchedItem1 = try keychain.persistentToken(withIdentifier: savedItem1.identifier)
let fetchedItem2 = try keychain.persistentToken(withIdentifier: savedItem2.identifier)
XCTAssertEqual(fetchedItem1, savedItem1, "Saved token not found in keychain")
XCTAssertEqual(fetchedItem2, savedItem2, "Saved token not found in keychain")
} catch {
Expand All @@ -141,14 +140,14 @@ class KeychainTests: XCTestCase {

// Remove the first token from the keychain
do {
try keychain.deletePersistentToken(savedItem1)
try keychain.delete(savedItem1)
} catch {
XCTFail("deletePersistentToken(_:) failed with error: \(error)")
}

do {
let checkItem1 = try keychain.persistentTokenWithIdentifier(savedItem1.identifier)
let checkItem2 = try keychain.persistentTokenWithIdentifier(savedItem2.identifier)
let checkItem1 = try keychain.persistentToken(withIdentifier: savedItem1.identifier)
let checkItem2 = try keychain.persistentToken(withIdentifier: savedItem2.identifier)
XCTAssertNil(checkItem1, "Token should not be in keychain: \(token1)")
XCTAssertNotNil(checkItem2, "Token should be in keychain: \(token2)")
} catch {
Expand All @@ -157,14 +156,14 @@ class KeychainTests: XCTestCase {

// Remove the second token from the keychain
do {
try keychain.deletePersistentToken(savedItem2)
try keychain.delete(savedItem2)
} catch {
XCTFail("deletePersistentToken(_:) failed with error: \(error)")
}

do {
let recheckItem1 = try keychain.persistentTokenWithIdentifier(savedItem1.identifier)
let recheckItem2 = try keychain.persistentTokenWithIdentifier(savedItem2.identifier)
let recheckItem1 = try keychain.persistentToken(withIdentifier: savedItem1.identifier)
let recheckItem2 = try keychain.persistentToken(withIdentifier: savedItem2.identifier)
XCTAssertNil(recheckItem1, "Token should not be in keychain: \(token1)")
XCTAssertNil(recheckItem2, "Token should not be in keychain: \(token2)")
} catch {
Expand All @@ -173,14 +172,14 @@ class KeychainTests: XCTestCase {

// Try to remove both tokens from the keychain again
do {
try keychain.deletePersistentToken(savedItem1)
try keychain.delete(savedItem1)
// The deletion should throw and this line should never be reached.
XCTFail("Removing again should fail: \(token1)")
} catch {
// An error thrown is the expected outcome
}
do {
try keychain.deletePersistentToken(savedItem2)
try keychain.delete(savedItem2)
// The deletion should throw and this line should never be reached.
XCTFail("Removing again should fail: \(token2)")
} catch {
Expand All @@ -205,9 +204,9 @@ class KeychainTests: XCTestCase {
let persistentToken2: PersistentToken
let persistentToken3: PersistentToken
do {
persistentToken1 = try keychain.addToken(token1)
persistentToken2 = try keychain.addToken(token2)
persistentToken3 = try keychain.addToken(token3)
persistentToken1 = try keychain.add(token1)
persistentToken2 = try keychain.add(token2)
persistentToken3 = try keychain.add(token3)
} catch {
XCTFail("addToken(_:) failed with error: \(error)")
return
Expand All @@ -222,9 +221,9 @@ class KeychainTests: XCTestCase {
}

do {
try keychain.deletePersistentToken(persistentToken1)
try keychain.deletePersistentToken(persistentToken2)
try keychain.deletePersistentToken(persistentToken3)
try keychain.delete(persistentToken1)
try keychain.delete(persistentToken2)
try keychain.delete(persistentToken3)
} catch {
XCTFail("deletePersistentToken(_:) failed with error: \(error)")
}
Expand Down
Loading