Skip to content

Commit

Permalink
Fix OAEP padding and update tests (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
nickneiman authored and ldiqual committed Dec 7, 2017
1 parent 8a50bb3 commit bdb1d1c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 5 deletions.
11 changes: 10 additions & 1 deletion SwiftyRSA/ClearMessage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,16 @@ public class ClearMessage: Message {
public func encrypted(with key: PublicKey, padding: Padding) throws -> EncryptedMessage {

let blockSize = SecKeyGetBlockSize(key.reference)
let maxChunkSize = (padding == []) ? blockSize : blockSize - 11

var maxChunkSize: Int
switch padding {
case []:
maxChunkSize = blockSize
case .OAEP:
maxChunkSize = blockSize - 42
default:
maxChunkSize = blockSize - 11
}

var decryptedDataAsArray = [UInt8](repeating: 0, count: data.count)
(data as NSData).getBytes(&decryptedDataAsArray, length: data.count)
Expand Down
10 changes: 10 additions & 0 deletions SwiftyRSATests/EncryptDecryptTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ class EncryptDecryptTests: XCTestCase {
XCTAssertEqual(decrypted.data, data)
}

func test_OAEP() throws {
let data = TestUtils.randomData(count: 2048)
let clearMessage = ClearMessage(data: data)

let encrypted = try clearMessage.encrypted(with: publicKey, padding: .OAEP)
let decrypted = try encrypted.decrypted(with: privateKey, padding: .OAEP)

XCTAssertEqual(decrypted.data, data)
}

func test_keyReferences() throws {
let data = TestUtils.randomData(count: 2048)
let clearMessage = ClearMessage(data: data)
Expand Down
9 changes: 5 additions & 4 deletions SwiftyRSATests/TestUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,12 @@ struct TestError: Error {

@objc
static public func randomData(count: Int) -> Data {
var data = Data(capacity: count)
data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Void in
_ = SecRandomCopyBytes(kSecRandomDefault, count, bytes)
var randomBytes = [UInt8](repeating: 0, count: count)
let status = SecRandomCopyBytes(kSecRandomDefault, count, &randomBytes)
if status != errSecSuccess {
XCTFail("Couldn't create random data")
}
return data
return Data(bytes: randomBytes)
}

static func assertThrows(type: SwiftyRSAError, file: StaticString = #file, line: UInt = #line, block: () throws -> Void) {
Expand Down

0 comments on commit bdb1d1c

Please sign in to comment.