Skip to content

Renaming PublicKey and PrivateKey Classes #257

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Source/ClearMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public class ClearMessage: Message {
/// - padding: Padding to use during the encryption
/// - Returns: Encrypted message
/// - Throws: SwiftyRSAError
public func encrypted(with key: PublicKey, padding: Padding) throws -> EncryptedMessage {
public func encrypted(with key: SwiftyRSA.PublicKey, padding: Padding) throws -> EncryptedMessage {

let blockSize = SecKeyGetBlockSize(key.reference)

Expand Down Expand Up @@ -104,7 +104,7 @@ public class ClearMessage: Message {
/// - digestType: Digest
/// - Returns: Signature of the clear message after signing it with the specified digest type.
/// - Throws: SwiftyRSAError
public func signed(with key: PrivateKey, digestType: Signature.DigestType) throws -> Signature {
public func signed(with key: SwiftyRSA.PrivateKey, digestType: Signature.DigestType) throws -> Signature {

let digest = self.digest(digestType: digestType)
let blockSize = SecKeyGetBlockSize(key.reference)
Expand Down Expand Up @@ -138,7 +138,7 @@ public class ClearMessage: Message {
/// - digestType: Digest type used for the signature
/// - Returns: Result of the verification
/// - Throws: SwiftyRSAError
public func verify(with key: PublicKey, signature: Signature, digestType: Signature.DigestType) throws -> Bool {
public func verify(with key: SwiftyRSA.PublicKey, signature: Signature, digestType: Signature.DigestType) throws -> Bool {

let digest = self.digest(digestType: digestType)
var digestBytes = [UInt8](repeating: 0, count: digest.count)
Expand Down
2 changes: 1 addition & 1 deletion Source/EncryptedMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class EncryptedMessage: Message {
/// - padding: Padding to use during the decryption
/// - Returns: Clear message
/// - Throws: SwiftyRSAError
public func decrypted(with key: PrivateKey, padding: Padding) throws -> ClearMessage {
public func decrypted(with key: SwiftyRSA.PrivateKey, padding: Padding) throws -> ClearMessage {
let blockSize = SecKeyGetBlockSize(key.reference)

var encryptedDataAsArray = [UInt8](repeating: 0, count: data.count)
Expand Down
102 changes: 52 additions & 50 deletions Source/PrivateKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,59 +7,61 @@
//

import Foundation

public class PrivateKey: Key {

/// Reference to the key within the keychain
public let reference: SecKey

/// Original data of the private key.
/// Note that it does not contain PEM headers and holds data as bytes, not as a base 64 string.
public let originalData: Data?

let tag: String?

/// Returns a PEM representation of the private key.
///
/// - Returns: Data of the key, PEM-encoded
/// - Throws: SwiftyRSAError
public func pemString() throws -> String {
let data = try self.data()
let pem = SwiftyRSA.format(keyData: data, withPemType: "RSA PRIVATE KEY")
return pem
}

/// Creates a private key with a keychain key reference.
/// This initializer will throw if the provided key reference is not a private RSA key.
///
/// - Parameter reference: Reference to the key within the keychain.
/// - Throws: SwiftyRSAError
public required init(reference: SecKey) throws {
public extension SwiftyRSA {
class PrivateKey: Key {

/// Reference to the key within the keychain
public let reference: SecKey

guard SwiftyRSA.isValidKeyReference(reference, forClass: kSecAttrKeyClassPrivate) else {
throw SwiftyRSAError.notAPrivateKey
/// Original data of the private key.
/// Note that it does not contain PEM headers and holds data as bytes, not as a base 64 string.
public let originalData: Data?

let tag: String?

/// Returns a PEM representation of the private key.
///
/// - Returns: Data of the key, PEM-encoded
/// - Throws: SwiftyRSAError
public func pemString() throws -> String {
let data = try self.data()
let pem = SwiftyRSA.format(keyData: data, withPemType: "RSA PRIVATE KEY")
return pem
}

self.reference = reference
self.tag = nil
self.originalData = nil
}

/// Creates a private key with a RSA public key data.
///
/// - Parameter data: Private key data
/// - Throws: SwiftyRSAError
required public init(data: Data) throws {
self.originalData = data
let tag = UUID().uuidString
self.tag = tag
let dataWithoutHeader = try SwiftyRSA.stripKeyHeader(keyData: data)
reference = try SwiftyRSA.addKey(dataWithoutHeader, isPublic: false, tag: tag)
}

deinit {
if let tag = tag {
SwiftyRSA.removeKey(tag: tag)
/// Creates a private key with a keychain key reference.
/// This initializer will throw if the provided key reference is not a private RSA key.
///
/// - Parameter reference: Reference to the key within the keychain.
/// - Throws: SwiftyRSAError
public required init(reference: SecKey) throws {

guard SwiftyRSA.isValidKeyReference(reference, forClass: kSecAttrKeyClassPrivate) else {
throw SwiftyRSAError.notAPrivateKey
}

self.reference = reference
self.tag = nil
self.originalData = nil
}

/// Creates a private key with a RSA public key data.
///
/// - Parameter data: Private key data
/// - Throws: SwiftyRSAError
required public init(data: Data) throws {
self.originalData = data
let tag = UUID().uuidString
self.tag = tag
let dataWithoutHeader = try SwiftyRSA.stripKeyHeader(keyData: data)
reference = try SwiftyRSA.addKey(dataWithoutHeader, isPublic: false, tag: tag)
}

deinit {
if let tag = tag {
SwiftyRSA.removeKey(tag: tag)
}
}
}

}
181 changes: 92 additions & 89 deletions Source/PublicKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,109 +8,112 @@

import Foundation

public class PublicKey: Key {

/// Reference to the key within the keychain
public let reference: SecKey

/// Data of the public key as provided when creating the key.
/// Note that if the key was created from a base64string / DER string / PEM file / DER file,
/// the data holds the actual bytes of the key, not any textual representation like PEM headers
/// or base64 characters.
public let originalData: Data?

let tag: String? // Only used on iOS 8/9

/// Returns a PEM representation of the public key.
///
/// - Returns: Data of the key, PEM-encoded
/// - Throws: SwiftyRSAError
public func pemString() throws -> String {
let data = try self.data()
let pem = SwiftyRSA.format(keyData: data, withPemType: "RSA PUBLIC KEY")
return pem
}

/// Creates a public key with a keychain key reference.
/// This initializer will throw if the provided key reference is not a public RSA key.
///
/// - Parameter reference: Reference to the key within the keychain.
/// - Throws: SwiftyRSAError
public required init(reference: SecKey) throws {

guard SwiftyRSA.isValidKeyReference(reference, forClass: kSecAttrKeyClassPublic) else {
throw SwiftyRSAError.notAPublicKey
}
public extension SwiftyRSA {
class PublicKey: Key {

self.reference = reference
self.tag = nil
self.originalData = nil
}

/// Data of the public key as returned by the keychain.
/// This method throws if SwiftyRSA cannot extract data from the key.
///
/// - Returns: Data of the public key as returned by the keychain.
/// - Throws: SwiftyRSAError
required public init(data: Data) throws {
/// Reference to the key within the keychain
public let reference: SecKey

let tag = UUID().uuidString
self.tag = tag
/// Data of the public key as provided when creating the key.
/// Note that if the key was created from a base64string / DER string / PEM file / DER file,
/// the data holds the actual bytes of the key, not any textual representation like PEM headers
/// or base64 characters.
public let originalData: Data?

self.originalData = data
let dataWithoutHeader = try SwiftyRSA.stripKeyHeader(keyData: data)
let tag: String? // Only used on iOS 8/9

reference = try SwiftyRSA.addKey(dataWithoutHeader, isPublic: true, tag: tag)
}

static let publicKeyRegex: NSRegularExpression? = {
let publicKeyRegex = "(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)"
return try? NSRegularExpression(pattern: publicKeyRegex, options: .dotMatchesLineSeparators)
}()

/// Takes an input string, scans for public key sections, and then returns a PublicKey for any valid keys found
/// - This method scans the file for public key armor - if no keys are found, an empty array is returned
/// - Each public key block found is "parsed" by `publicKeyFromPEMString()`
/// - should that method throw, the error is _swallowed_ and not rethrown
///
/// - parameter pemString: The string to use to parse out values
///
/// - returns: An array of `PublicKey` objects
public static func publicKeys(pemEncoded pemString: String) -> [PublicKey] {
/// Returns a PEM representation of the public key.
///
/// - Returns: Data of the key, PEM-encoded
/// - Throws: SwiftyRSAError
public func pemString() throws -> String {
let data = try self.data()
let pem = SwiftyRSA.format(keyData: data, withPemType: "RSA PUBLIC KEY")
return pem
}

// If our regexp isn't valid, or the input string is empty, we can't move forward…
guard let publicKeyRegexp = publicKeyRegex, pemString.count > 0 else {
return []
/// Creates a public key with a keychain key reference.
/// This initializer will throw if the provided key reference is not a public RSA key.
///
/// - Parameter reference: Reference to the key within the keychain.
/// - Throws: SwiftyRSAError
public required init(reference: SecKey) throws {

guard SwiftyRSA.isValidKeyReference(reference, forClass: kSecAttrKeyClassPublic) else {
throw SwiftyRSAError.notAPublicKey
}

self.reference = reference
self.tag = nil
self.originalData = nil
}

let all = NSRange(
location: 0,
length: pemString.count
)
/// Data of the public key as returned by the keychain.
/// This method throws if SwiftyRSA cannot extract data from the key.
///
/// - Returns: Data of the public key as returned by the keychain.
/// - Throws: SwiftyRSAError
required public init(data: Data) throws {

let tag = UUID().uuidString
self.tag = tag

self.originalData = data
let dataWithoutHeader = try SwiftyRSA.stripKeyHeader(keyData: data)

reference = try SwiftyRSA.addKey(dataWithoutHeader, isPublic: true, tag: tag)
}

let matches = publicKeyRegexp.matches(
in: pemString,
options: NSRegularExpression.MatchingOptions(rawValue: 0),
range: all
)
static let publicKeyRegex: NSRegularExpression? = {
let publicKeyRegex = "(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)"
return try? NSRegularExpression(pattern: publicKeyRegex, options: .dotMatchesLineSeparators)
}()

let keys = matches.compactMap { result -> PublicKey? in
/// Takes an input string, scans for public key sections, and then returns a PublicKey for any valid keys found
/// - This method scans the file for public key armor - if no keys are found, an empty array is returned
/// - Each public key block found is "parsed" by `publicKeyFromPEMString()`
/// - should that method throw, the error is _swallowed_ and not rethrown
///
/// - parameter pemString: The string to use to parse out values
///
/// - returns: An array of `PublicKey` objects
public static func publicKeys(pemEncoded pemString: String) -> [PublicKey] {

let match = result.range(at: 1)
let start = pemString.index(pemString.startIndex, offsetBy: match.location)
let end = pemString.index(start, offsetBy: match.length)
// If our regexp isn't valid, or the input string is empty, we can't move forward…
guard let publicKeyRegexp = publicKeyRegex, pemString.count > 0 else {
return []
}

let thisKey = pemString[start..<end]
let all = NSRange(
location: 0,
length: pemString.count
)

return try? PublicKey(pemEncoded: String(thisKey))
let matches = publicKeyRegexp.matches(
in: pemString,
options: NSRegularExpression.MatchingOptions(rawValue: 0),
range: all
)

let keys = matches.compactMap { result -> PublicKey? in

let match = result.range(at: 1)
let start = pemString.index(pemString.startIndex, offsetBy: match.location)
let end = pemString.index(start, offsetBy: match.length)

let thisKey = pemString[start..<end]

return try? PublicKey(pemEncoded: String(thisKey))
}

return keys
}

return keys
}

deinit {
if let tag = tag {
SwiftyRSA.removeKey(tag: tag)
deinit {
if let tag = tag {
SwiftyRSA.removeKey(tag: tag)
}
}
}

}
Loading