Skip to content

Commit

Permalink
Merge pull request #39 from IBM-Swift/base64Key
Browse files Browse the repository at this point in the history
fix: Add PEM header for base64 private key on linux
  • Loading branch information
billabt authored Mar 6, 2019
2 parents 5e9eb0e + 889201a commit 6a42189
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
14 changes: 12 additions & 2 deletions Sources/CryptorRSA/CryptorRSAKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -428,11 +428,21 @@ extension CryptorRSA {
///
public class func createPrivateKey(withBase64 base64String: String) throws -> PrivateKey {

guard let data = Data(base64Encoded: base64String, options: [.ignoreUnknownCharacters]) else {
guard let dataIn = Data(base64Encoded: base64String, options: [.ignoreUnknownCharacters]) else {

throw Error(code: ERR_INIT_PK, reason: "Couldn't decode base 64 string")
}


#if os(Linux)

let data = CryptorRSA.convertDerToPem(from: dataIn, type: .privateType)

#else

let data = dataIn

#endif

return try PrivateKey(with: data)
}

Expand Down
17 changes: 16 additions & 1 deletion Tests/CryptorRSATests/CryptorRSATests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,21 @@ class CryptorRSATests: XCTestCase {
XCTAssertTrue(privateKey!.type == .privateType)
}
}

func test_private_initWithBase64() throws {

let path = CryptorRSATests.getFilePath(for: "private", ofType: "pem")
XCTAssertNotNil(path)

if let filePath = path {
let str = try String(contentsOf: filePath, encoding: .utf8)
let strippedstr = String(str.filter { !" \n\t\r".contains($0) })
let headerlessStr = String(strippedstr.dropFirst(28).dropLast(26))
let privateKey = try? CryptorRSA.createPrivateKey(withBase64: headerlessStr)
XCTAssertNotNil(privateKey)
XCTAssertTrue(privateKey?.type == .privateType)
}
}

func test_private_initWithPEMStringHeaderless() throws {

Expand Down Expand Up @@ -721,7 +736,7 @@ cSNAr2BBC8bJ9AfZnRu9+Y1/VyXY91R95bQoMFfgwZdMUEyuL5gG524QplqF
("test_public_initWithCertificateName", test_public_initWithCertificateName),
("test_public_initWithCertificateName2", test_public_initWithCertificateName2),
("test_private_initWithPEMString", test_private_initWithPEMString),

("test_private_initWithBase64", test_private_initWithBase64),
// ("test_private_initWithPEMStringHeaderless", test_private_initWithPEMStringHeaderless),
("test_private_initWithPEMName", test_private_initWithPEMName),
("test_private_initWithDERName", test_private_initWithDERName),
Expand Down

0 comments on commit 6a42189

Please sign in to comment.