Skip to content

Commit

Permalink
Update to Swift 5.1, fix crash on Linux (#53)
Browse files Browse the repository at this point in the history
* ci: Update to Swift 5.1

* Handle failure of d2i_PUBKEY_bio

* Add test for #52

---------

Co-authored-by: Danny Sung <[email protected]>
  • Loading branch information
djones6 and dannys42 authored Nov 19, 2024
1 parent ccb772a commit 8d2f8eb
Show file tree
Hide file tree
Showing 4 changed files with 75 additions and 34 deletions.
2 changes: 1 addition & 1 deletion .swift-version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5.0.2
5.1
3 changes: 3 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ matrix:
- os: osx
osx_image: xcode14.2
sudo: required
- os: osx
osx_image: xcode11
sudo: required
env: SWIFT_SNAPSHOT=$SWIFT_DEVELOPMENT_SNAPSHOT

before_install:
Expand Down
45 changes: 21 additions & 24 deletions Sources/CryptorRSA/CryptorRSAUtilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -62,37 +62,34 @@ public extension CryptorRSA {
// Create a memory BIO...
let bio = BIO_new(BIO_s_mem())

defer {
BIO_free(bio)
}
defer {
BIO_free(bio)
}
// Create a BIO object with the key data...
try headerKey.withUnsafeBytes() { (buffer: UnsafeRawBufferPointer) in

let len = BIO_write(bio, buffer.baseAddress?.assumingMemoryBound(to: UInt8.self), Int32(headerKey.count))
guard len != 0 else {
let source = "Couldn't create BIO reference from key data"
if let reason = CryptorRSA.getLastError(source: source) {

throw Error(code: ERR_ADD_KEY, reason: reason)
}
throw Error(code: ERR_ADD_KEY, reason: source + ": No OpenSSL error reported.")
}
guard len != 0 else {
let source = "Couldn't create BIO reference from key data"
if let reason = CryptorRSA.getLastError(source: source) {
throw Error(code: ERR_ADD_KEY, reason: reason)
}
throw Error(code: ERR_ADD_KEY, reason: source + ": No OpenSSL error reported.")
}
// The below is equivalent of BIO_flush...
BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nil)
BIO_ctrl(bio, BIO_CTRL_FLUSH, 0, nil)
}

var evp_key: OpaquePointer?

// Read in the key data and process depending on key type...
if type == .publicType {

evp_key = .init(d2i_PUBKEY_bio(bio, nil))

} else {

evp_key = .init(d2i_PrivateKey_bio(bio, nil))
}
return evp_key
// Read in the key data and process depending on key type...
var keyMaybe = (type == .publicType ? d2i_PUBKEY_bio(bio, nil) : d2i_PrivateKey_bio(bio, nil))
guard let key = keyMaybe else {
let source = "Failed to create key from BIO"
if let reason = CryptorRSA.getLastError(source: source) {
throw Error(code: ERR_ADD_KEY, reason: reason)
}
throw Error(code: ERR_ADD_KEY, reason: source + ": No OpenSSL error reported.")
}
return .init(key)
}

///
Expand Down
59 changes: 50 additions & 9 deletions Tests/CryptorRSATests/CryptorRSATests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -757,15 +757,27 @@ cSNAr2BBC8bJ9AfZnRu9+Y1/VyXY91R95bQoMFfgwZdMUEyuL5gG524QplqF
let (tempPrivKey, tempPubKey) = try CryptorRSA.makeKeyPair(bitSize)
let privString = tempPrivKey.pemString
let pubString = tempPubKey.pemString
let privKey = try CryptorRSA.createPrivateKey(withPEM: privString)
let pubKey = try CryptorRSA.createPublicKey(withPEM: pubString)
let str = "Plain Text"
let plainText = try CryptorRSA.createPlaintext(with: str, using: .utf8)
let encrypted = try plainText.encrypted(with: pubKey, algorithm: .gcm)
let decrypted = try encrypted?.decrypted(with: privKey, algorithm: .gcm)
XCTAssertNotNil(decrypted)
let decryptedString = try decrypted?.string(using: .utf8)
XCTAssertEqual(decryptedString, str)
do {
let privKey = try CryptorRSA.createPrivateKey(withPEM: privString)
do {
let pubKey = try CryptorRSA.createPublicKey(withPEM: pubString)
let str = "Plain Text"
do {
let plainText = try CryptorRSA.createPlaintext(with: str, using: .utf8)
let encrypted = try plainText.encrypted(with: pubKey, algorithm: .gcm)
let decrypted = try encrypted?.decrypted(with: privKey, algorithm: .gcm)
XCTAssertNotNil(decrypted)
let decryptedString = try decrypted?.string(using: .utf8)
XCTAssertEqual(decryptedString, str)
} catch {
XCTFail("Encryption / decryption failed for bitSize: \(bitSize.bits): \(error)")
}
} catch {
XCTFail("createPublicKey failed for bitSize: \(bitSize.bits): \(error), PEM: '\(pubString)'")
}
} catch {
XCTFail("createPrivateKey failed for bitSize: \(bitSize.bits): \(error), PEM: '\(privString)'")
}
} catch {
XCTFail("test_makeKeyPair failed for bitSize: \(bitSize.bits), with error: \(error)")
}
Expand All @@ -774,6 +786,34 @@ cSNAr2BBC8bJ9AfZnRu9+Y1/VyXY91R95bQoMFfgwZdMUEyuL5gG524QplqF

}

// Test that when the data for a key has a value of 0x30 in byte 27, it is not
// erroneously interpreted as pkcs8 by stripX509CertificateHeader (whereby the
// first 26 bytes are dropped).
// See https://github.com/IBM-Swift/BlueRSA/issues/52
func testSpecificPEM() {
let pemString = """
-----BEGIN RSA PUBLIC KEY-----
MIIBigKCAYEAsdrDG5WLDpbIa5cHIwhFvkkwpWG3ULikyMsNWUq0/d1uaRdlemgvS
u21PqwDhBsgFjBn8ENQsOQpr5Bm2tC2XIchKPjEnsA3WsQ2iIkbDzrmbj5r2z1iiy
n/veMZEG0+Dg5H91I+2SG7c406rUgU00py/Y/C/aQCJonhpEolvuF3tgUt6/6X1mz
Y2ANwBzm3Zv9JoK0nAWZFqTkj9WrUXQprBi3G/mTLMaOScZzSig+rr8uxyl3TnV+X
bFuqD6hweWrCDOWJFZOHzflflCN/dFGHcUZqJNygjSY0LBBN7G2ES6XRlrr0OPypU
otmFEXJ1djQdlAVLc/LofhpVdXKW8zjm/Gj4guSYDiNNSSG8KgpCbTPJ4ZQGiTrx2
qse4PDC6PckHebpTXMUYSXLacoTEpAI9EONIuG6ThOkIyGO8elHVknhkZZZD0SIC3
jK/J8XlsTSWFGkif8W0PQJ5amyK7C/8eWZFwA7gLpNvR4BqnsY4a+dIw4a/HD0RKQ
AqJRAgMBAAE=
-----END RSA PUBLIC KEY-----
"""
let data1 = Data(base64Encoded: pemString) ?? Data()
print("data1 count=\(data1.count)")
do {
let pubKey = try CryptorRSA.createPublicKey(withPEM: pemString)
print("pemString1 successful")
} catch {
XCTFail("Error creating public key from pemString: \(error)")
}
}

// MARK: Test Utilities

struct TestError: Error {
Expand Down Expand Up @@ -887,6 +927,7 @@ cSNAr2BBC8bJ9AfZnRu9+Y1/VyXY91R95bQoMFfgwZdMUEyuL5gG524QplqF
("test_verifyExtenalPSSSignature", test_verifyExtenalPSSSignature),
("test_verifyAppIDToken", test_verifyAppIDToken),
("test_makeKeyPair", test_makeKeyPair),
("testSpecificPEM", testSpecificPEM),
]
}
}
Expand Down

0 comments on commit 8d2f8eb

Please sign in to comment.