More idiomatic use of XCTest (#15)

This commit is contained in:
Zev Eisenberg authored and GitHub committed 2020-02-14 10:03:41 +00:00
1 parent 64a1a98e47
commit b6b60c3938
17 files changed
+487 -365

No files matched your search

@@ -41,7 +41,7 @@ struct AESGCMTestVector: Codable {
}
class AESGCMTests: XCTestCase {
func testingBadKeySize() {
func testBadKeySize() {
let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!
let key = SymmetricKey(size: .init(bitCount: 304))
let nonce = AES.GCM.Nonce()
@@ -53,25 +53,25 @@ class AESGCMTests: XCTestCase {
let ciphertext = Array("This is some weird ciphertext".utf8)
let tag = Array(repeating: UInt8(0), count: 16)
let regularNonce = try AES.GCM.Nonce(data: Array(repeating: 0, count: 12))
let longNonce = try AES.GCM.Nonce(data: Array(repeating: 0, count: 13))
let regularNonce = try orFail { try AES.GCM.Nonce(data: Array(repeating: 0, count: 12)) }
let longNonce = try orFail { try AES.GCM.Nonce(data: Array(repeating: 0, count: 13)) }
XCTAssertNotNil(try AES.GCM.SealedBox(nonce: regularNonce, ciphertext: ciphertext, tag: tag).combined)
XCTAssertNil(try AES.GCM.SealedBox(nonce: longNonce, ciphertext: ciphertext, tag: tag).combined)
}
func testEncryptDecrypt() {
func testEncryptDecrypt() throws {
let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!
let key = SymmetricKey(size: .bits256)
let nonce = AES.GCM.Nonce()
let ciphertext = try! AES.GCM.seal(plaintext, using: key, nonce: nonce)
let recoveredPlaintext = try! AES.GCM.open(ciphertext, using: key, authenticating: Data())
let recoveredPlaintextWithoutAAD = try! AES.GCM.open(ciphertext, using: key)
let ciphertext = try orFail { try AES.GCM.seal(plaintext, using: key, nonce: nonce) }
let recoveredPlaintext = try orFail { try AES.GCM.open(ciphertext, using: key, authenticating: Data()) }
let recoveredPlaintextWithoutAAD = try orFail { try AES.GCM.open(ciphertext, using: key) }
XCTAssert(recoveredPlaintext == plaintext)
XCTAssert(recoveredPlaintextWithoutAAD == plaintext)
XCTAssertEqual(recoveredPlaintext, plaintext)
XCTAssertEqual(recoveredPlaintextWithoutAAD, plaintext)
}
func testExtractingBytesFromNonce() throws {
@@ -80,8 +80,8 @@ class AESGCMTests: XCTestCase {
let testNonceBytes = Array(UInt8(0)..<UInt8(12))
let (contiguousNonceBytes, discontiguousNonceBytes) = testNonceBytes.asDataProtocols()
let nonceFromContiguous = try AES.GCM.Nonce(data: contiguousNonceBytes)
let nonceFromDiscontiguous = try AES.GCM.Nonce(data: discontiguousNonceBytes)
let nonceFromContiguous = try orFail { try AES.GCM.Nonce(data: contiguousNonceBytes) }
let nonceFromDiscontiguous = try orFail { try AES.GCM.Nonce(data: discontiguousNonceBytes) }
XCTAssertEqual(Array(nonceFromContiguous), testNonceBytes)
XCTAssertEqual(Array(nonceFromDiscontiguous), testNonceBytes)
@@ -98,8 +98,8 @@ class AESGCMTests: XCTestCase {
let ciphertext = Array("This pretty clearly isn't ciphertext, but sure why not".utf8)
let (contiguousCiphertext, discontiguousCiphertext) = ciphertext.asDataProtocols()
let contiguousSB = try AES.GCM.SealedBox(combined: contiguousCiphertext)
let discontiguousSB = try AES.GCM.SealedBox(combined: discontiguousCiphertext)
let contiguousSB = try orFail { try AES.GCM.SealedBox(combined: contiguousCiphertext) }
let discontiguousSB = try orFail { try AES.GCM.SealedBox(combined: discontiguousCiphertext) }
XCTAssertEqual(contiguousSB.combined, discontiguousSB.combined)
XCTAssertEqual(Array(contiguousSB.nonce), Array(discontiguousSB.nonce))
XCTAssertEqual(contiguousSB.ciphertext, discontiguousSB.ciphertext)
@@ -123,10 +123,10 @@ class AESGCMTests: XCTestCase {
let (contiguousTag, discontiguousTag) = tag.asDataProtocols()
// Two separate data protocol inputs means we end up with 4 boxes.
let contiguousContiguous = try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: contiguousTag)
let discontiguousContiguous = try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: contiguousTag)
let contiguousDiscontiguous = try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: discontiguousTag)
let discontiguousDiscontiguous = try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: discontiguousTag)
let contiguousContiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: contiguousTag) }
let discontiguousContiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: contiguousTag) }
let contiguousDiscontiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: discontiguousTag) }
let discontiguousDiscontiguous = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: discontiguousTag) }
// To avoid the comparison count getting too nuts, we use the combined representation. By the transitive
// property we only need three comparisons.
@@ -143,19 +143,18 @@ class AESGCMTests: XCTestCase {
}
// They work fine for the ciphertext though.
let weirdBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: DispatchData.empty, tag: tag)
let weirdBox = try orFail { try AES.GCM.SealedBox(nonce: nonce, ciphertext: DispatchData.empty, tag: tag) }
XCTAssertEqual(weirdBox.ciphertext, Data())
}
func testRoundTripDataProtocols() throws {
func roundTrip<Message: DataProtocol, AAD: DataProtocol>(message: Message, aad: AAD) {
func roundTrip<Message: DataProtocol, AAD: DataProtocol>(message: Message, aad: AAD, file: StaticString = #file, line: UInt = #line) throws {
let key = SymmetricKey(size: .bits256)
let nonce = AES.GCM.Nonce()
let ciphertext = try orFail(file: file, line: line) { try AES.GCM.seal(message, using: key, nonce: nonce, authenticating: aad) }
let recoveredPlaintext = try orFail(file: file, line: line) { try AES.GCM.open(ciphertext, using: key, authenticating: aad) }
let ciphertext = try! AES.GCM.seal(message, using: key, nonce: nonce, authenticating: aad)
let recoveredPlaintext = try! AES.GCM.open(ciphertext, using: key, authenticating: aad)
XCTAssert(Array(recoveredPlaintext) == Array(message))
XCTAssertEqual(Array(recoveredPlaintext), Array(message), file: file, line: line)
}
let message = Array("Hello, world, it's AES-GCM!".utf8)
@@ -163,76 +162,79 @@ class AESGCMTests: XCTestCase {
let (contiguousMessage, discontiguousMessage) = message.asDataProtocols()
let (contiguousAad, discontiguousAad) = aad.asDataProtocols()
roundTrip(message: contiguousMessage, aad: contiguousAad)
roundTrip(message: discontiguousMessage, aad: contiguousAad)
roundTrip(message: contiguousMessage, aad: discontiguousAad)
roundTrip(message: discontiguousMessage, aad: discontiguousAad)
_ = try orFail { try roundTrip(message: contiguousMessage, aad: contiguousAad) }
_ = try orFail { try roundTrip(message: discontiguousMessage, aad: contiguousAad) }
_ = try orFail { try roundTrip(message: contiguousMessage, aad: discontiguousAad) }
_ = try orFail { try roundTrip(message: discontiguousMessage, aad: discontiguousAad) }
}
func testWycheproof() throws {
wycheproofTest(bundleType: self,
jsonName: "aes_gcm_test",
testFunction: { (group: AEADTestGroup) in
for testVector in group.tests {
var msg = Data()
var aad = Data()
var ct: [UInt8] = []
var tag: [UInt8] = []
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "aes_gcm_test",
testFunction: { (group: AEADTestGroup) in
for testVector in group.tests {
var msg = Data()
var aad = Data()
var ct: [UInt8] = []
var tag: [UInt8] = []
do {
let key = try SymmetricKey(data: Array(hexString: testVector.key))
XCTAssertNotNil(key)
let nonceData = try Array(hexString: testVector.iv)
let nonce: AES.GCM.Nonce
do {
nonce = try AES.GCM.Nonce(data: nonceData)
} catch {
XCTAssertLessThan(nonceData.count, 12)
continue
}
if testVector.ct.count > 0 {
ct = try Array(hexString: testVector.ct)
}
if testVector.msg.count > 0 {
msg = try Data(hexString: testVector.msg)
}
if testVector.aad.count > 0 {
aad = try Data(hexString: testVector.aad)
}
if testVector.tag.count > 0 {
tag = try Array(hexString: testVector.tag)
}
let sb = try AES.GCM.seal(msg, using: key, nonce: nonce, authenticating: aad)
XCTAssertEqual(Data(ct), sb.ciphertext)
if (testVector.result == "valid") {
XCTAssertEqual(Data(tag), sb.tag)
}
do {
let key = try! SymmetricKey(data: Array(hexString: testVector.key))
XCTAssertNotNil(key)
let recovered_pt = try AES.GCM.open(AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag), using: key, authenticating: aad)
let nonceData = try Array(hexString: testVector.iv)
let nonce: AES.GCM.Nonce
do {
nonce = try AES.GCM.Nonce(data: nonceData)
} catch {
XCTAssert(nonceData.count < 12)
continue
}
if testVector.ct.count > 0 {
ct = try! Array(hexString: testVector.ct)
}
if testVector.msg.count > 0 {
msg = try! Data(hexString: testVector.msg)
}
if testVector.aad.count > 0 {
aad = try! Data(hexString: testVector.aad)
}
if testVector.tag.count > 0 {
tag = try! Array(hexString: testVector.tag)
}
let sb = try! AES.GCM.seal(msg, using: key, nonce: nonce, authenticating: aad)
XCTAssert(Data(ct) == sb.ciphertext)
if (testVector.result == "valid") {
XCTAssert(Data(tag) == sb.tag)
}
do {
let recovered_pt = try AES.GCM.open(AES.GCM.SealedBox(nonce: nonce, ciphertext: ct, tag: tag), using: key, authenticating: aad)
if (testVector.result == "valid" || testVector.result == "acceptable") {
XCTAssert(recovered_pt == msg)
} else {
XCTAssert(false)
}
} catch {
XCTAssert(testVector.result == "invalid")
if (testVector.result == "valid" || testVector.result == "acceptable") {
XCTAssertEqual(recovered_pt, msg)
} else {
XCTFail()
}
} catch {
XCTAssert(testVector.result == "invalid" || testVector.iv == "")
return
XCTAssertEqual(testVector.result, "invalid")
}
} catch {
XCTAssert(testVector.result == "invalid" || testVector.iv == "")
return
}
})
}
})
}
}
}
@@ -23,7 +23,7 @@ import Crypto
#endif
class ChaChaPolyTests: XCTestCase {
func testIncorrectKeySize() {
func testIncorrectKeySize() throws {
let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!
let wrongKey = SymmetricKey(size: .bits128)
@@ -31,7 +31,7 @@ class ChaChaPolyTests: XCTestCase {
let nonce = ChaChaPoly.Nonce()
XCTAssertThrowsError(try ChaChaPoly.seal(plaintext, using: wrongKey, nonce: nonce))
let message = try! ChaChaPoly.seal(plaintext, using: key, nonce: nonce)
let message = try orFail { try ChaChaPoly.seal(plaintext, using: key, nonce: nonce) }
XCTAssertThrowsError(try ChaChaPoly.open(message, using: wrongKey))
XCTAssertNoThrow(try ChaChaPoly.open(message, using: key))
@@ -43,8 +43,8 @@ class ChaChaPolyTests: XCTestCase {
let testNonceBytes = Array(UInt8(0)..<UInt8(12))
let (contiguousNonceBytes, discontiguousNonceBytes) = testNonceBytes.asDataProtocols()
let nonceFromContiguous = try ChaChaPoly.Nonce(data: contiguousNonceBytes)
let nonceFromDiscontiguous = try ChaChaPoly.Nonce(data: discontiguousNonceBytes)
let nonceFromContiguous = try orFail { try ChaChaPoly.Nonce(data: contiguousNonceBytes) }
let nonceFromDiscontiguous = try orFail { try ChaChaPoly.Nonce(data: discontiguousNonceBytes) }
XCTAssertEqual(Array(nonceFromContiguous), testNonceBytes)
XCTAssertEqual(Array(nonceFromDiscontiguous), testNonceBytes)
@@ -57,24 +57,24 @@ class ChaChaPolyTests: XCTestCase {
}
}
func testEncryptDecrypt() {
func testEncryptDecrypt() throws {
let plaintext: Data = "Some Super Secret Message".data(using: String.Encoding.utf8)!
let key = SymmetricKey(size: .bits256)
let nonce = ChaChaPoly.Nonce()
let ciphertext = try! ChaChaPoly.seal(plaintext, using: key, nonce: nonce, authenticating: Data())
let recoveredPlaintext = try! ChaChaPoly.open(ciphertext, using: key, authenticating: Data())
let ciphertext = try orFail { try ChaChaPoly.seal(plaintext, using: key, nonce: nonce, authenticating: Data()) }
let recoveredPlaintext = try orFail { try ChaChaPoly.open(ciphertext, using: key, authenticating: Data()) }
XCTAssert(recoveredPlaintext == plaintext)
XCTAssertEqual(recoveredPlaintext, plaintext)
}
func testUserConstructedSealedBoxesCombined() throws {
let ciphertext = Array("This pretty clearly isn't ciphertext, but sure why not".utf8)
let (contiguousCiphertext, discontiguousCiphertext) = ciphertext.asDataProtocols()
let contiguousSB = try ChaChaPoly.SealedBox(combined: contiguousCiphertext)
let discontiguousSB = try ChaChaPoly.SealedBox(combined: discontiguousCiphertext)
let contiguousSB = try orFail { try ChaChaPoly.SealedBox(combined: contiguousCiphertext) }
let discontiguousSB = try orFail { try ChaChaPoly.SealedBox(combined: discontiguousCiphertext) }
XCTAssertEqual(contiguousSB.combined, discontiguousSB.combined)
XCTAssertEqual(Array(contiguousSB.nonce), Array(discontiguousSB.nonce))
XCTAssertEqual(contiguousSB.ciphertext, discontiguousSB.ciphertext)
@@ -98,10 +98,18 @@ class ChaChaPolyTests: XCTestCase {
let (contiguousTag, discontiguousTag) = tag.asDataProtocols()
// Two separate data protocol inputs means we end up with 4 boxes.
let contiguousContiguous = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: contiguousTag)
let discontiguousContiguous = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: contiguousTag)
let contiguousDiscontiguous = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: discontiguousTag)
let discontiguousDiscontiguous = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: discontiguousTag)
let contiguousContiguous = try orFail {
try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: contiguousTag)
}
let discontiguousContiguous = try orFail {
try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: contiguousTag)
}
let contiguousDiscontiguous = try orFail {
try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: contiguousCiphertext, tag: discontiguousTag)
}
let discontiguousDiscontiguous = try orFail {
try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: discontiguousCiphertext, tag: discontiguousTag)
}
// To avoid the comparison count getting too nuts, we use the combined representation. By the transitive
// property we only need three comparisons.
@@ -118,19 +126,19 @@ class ChaChaPolyTests: XCTestCase {
}
// They work fine for the ciphertext though.
let weirdBox = try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: DispatchData.empty, tag: tag)
let weirdBox = try orFail { try ChaChaPoly.SealedBox(nonce: nonce, ciphertext: DispatchData.empty, tag: tag) }
XCTAssertEqual(weirdBox.ciphertext, Data())
}
func testRoundTripDataProtocols() throws {
func roundTrip<Message: DataProtocol, AAD: DataProtocol>(message: Message, aad: AAD) {
func roundTrip<Message: DataProtocol, AAD: DataProtocol>(message: Message, aad: AAD, file: StaticString = #file, line: UInt = #line) throws {
let key = SymmetricKey(size: .bits256)
let nonce = ChaChaPoly.Nonce()
let ciphertext = try! ChaChaPoly.seal(message, using: key, nonce: nonce, authenticating: aad)
let recoveredPlaintext = try! ChaChaPoly.open(ciphertext, using: key, authenticating: aad)
let ciphertext = try orFail(file: file, line: line) { try ChaChaPoly.seal(message, using: key, nonce: nonce, authenticating: aad) }
let recoveredPlaintext = try orFail(file: file, line: line) { try ChaChaPoly.open(ciphertext, using: key, authenticating: aad) }
XCTAssert(Array(recoveredPlaintext) == Array(message))
XCTAssertEqual(Array(recoveredPlaintext), Array(message), file: file, line: line)
}
let message = Array("Hello, world, it's ChaCha!".utf8)
@@ -138,21 +146,24 @@ class ChaChaPolyTests: XCTestCase {
let (contiguousMessage, discontiguousMessage) = message.asDataProtocols()
let (contiguousAad, discontiguousAad) = aad.asDataProtocols()
roundTrip(message: contiguousMessage, aad: contiguousAad)
roundTrip(message: discontiguousMessage, aad: contiguousAad)
roundTrip(message: contiguousMessage, aad: discontiguousAad)
roundTrip(message: discontiguousMessage, aad: discontiguousAad)
_ = try orFail { try roundTrip(message: contiguousMessage, aad: contiguousAad) }
_ = try orFail { try roundTrip(message: discontiguousMessage, aad: contiguousAad) }
_ = try orFail { try roundTrip(message: contiguousMessage, aad: discontiguousAad) }
_ = try orFail { try roundTrip(message: discontiguousMessage, aad: discontiguousAad) }
}
func testWycheproof() throws {
wycheproofTest(bundleType: self,
jsonName: "chacha20_poly1305_test",
testFunction: { (group: AEADTestGroup) in
testGroup(group: group)
})
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "chacha20_poly1305_test",
testFunction: { (group: AEADTestGroup) in
_ = try orFail { try testGroup(group: group) }
})
}
}
func testGroup(group: AEADTestGroup) {
func testGroup(group: AEADTestGroup) throws {
for testVector in group.tests {
var msg: Data = Data()
var aad: Data = Data()
@@ -164,47 +175,45 @@ class ChaChaPolyTests: XCTestCase {
do {
nonce = try ChaChaPoly.Nonce(data: Array(hexString: testVector.iv))
} catch {
XCTAssert(testVector.result == "invalid")
XCTAssertEqual(testVector.result, "invalid")
return
}
if testVector.ct.count > 0 {
ct = try! Array(hexString: testVector.ct)
ct = try orFail { try Array(hexString: testVector.ct) }
}
if testVector.msg.count > 0 {
msg = try! Data(hexString: testVector.msg)
msg = try orFail { try Data(hexString: testVector.msg) }
}
if testVector.aad.count > 0 {
aad = try! Data(hexString: testVector.aad)
aad = try orFail { try Data(hexString: testVector.aad) }
}
if testVector.tag.count > 0 {
tag = try! Array(hexString: testVector.tag)
tag = try orFail { try Array(hexString: testVector.tag) }
}
let key = try! SymmetricKey(data: Array(hexString: testVector.key))
let key = try orFail { try SymmetricKey(data: Array(hexString: testVector.key)) }
XCTAssertNotNil(key)
let sb = try! ChaChaPoly.seal(msg, using: key, nonce: nonce, authenticating: aad)
let sb = try orFail { try ChaChaPoly.seal(msg, using: key, nonce: nonce, authenticating: aad) }
XCTAssert(Data(ct) == sb.ciphertext)
XCTAssertEqual(Data(ct), sb.ciphertext)
if (testVector.result == "valid") {
XCTAssert(Data(tag) == sb.tag)
XCTAssertEqual(Data(tag), sb.tag)
}
do {
let recovered_pt = try ChaChaPoly.open(ChaChaPoly.SealedBox(nonce: nonce, ciphertext: ct, tag: tag), using: key, authenticating: aad)
if (testVector.result == "valid" || testVector.result == "acceptable") {
XCTAssert(recovered_pt == msg)
} else {
XCTAssert(true)
XCTAssertEqual(recovered_pt, msg)
}
} catch {
XCTAssert(testVector.result == "invalid")
XCTAssertEqual(testVector.result, "invalid")
}
}
}
@@ -98,6 +98,8 @@ final class ArbitraryPrecisionIntegerTests: XCTestCase {
let one = ArbitraryPrecisionInteger(1)
let two = ArbitraryPrecisionInteger(2)
// Not using XCTAssertLessThan and friends
// because we want to test these operators specifically.
XCTAssertTrue(one < two)
XCTAssertTrue(one <= two)
XCTAssertFalse(one < one)
+33 -27
View File
@@ -50,39 +50,45 @@ func testVectorForAlgorithm<H: HashFunction>(hashFunction: H.Type) throws -> Str
}
class DigestsTests: XCTestCase {
func testHashFunctionWithVector<H: HashFunction>(hf: H.Type, data: Data, testVector: String) {
func assertHashFunctionWithVector<H: HashFunction>(hf: H.Type, data: Data, testVector: String, file: StaticString = #file, line: UInt = #line) throws {
var h = hf.init()
h.update(data: data)
let result = h.finalize()
let testBytes = try! Array(hexString: testVector)
let testBytes = try orFail(file: file, line: line) { try Array(hexString: testVector) }
XCTAssert(testBytes == Array(result))
XCTAssert(Array(H.hash(data: data)) == testBytes)
XCTAssertEqual(testBytes, Array(result), file: file, line: line)
XCTAssertEqual(Array(H.hash(data: data)), testBytes, file: file, line: line)
let (contiguousResult, discontiguousResult) = testBytes.asDataProtocols()
XCTAssert(result == contiguousResult)
XCTAssert(result == discontiguousResult)
XCTAssertFalse(result == DispatchData.empty)
XCTAssert(result == contiguousResult, file: file, line: line)
XCTAssert(result == discontiguousResult, file: file, line: line)
XCTAssertFalse(result == DispatchData.empty, file: file, line: line)
}
func testMD5() {
XCTAssert(Data(Insecure.MD5.hash(data: Data())).count == Insecure.MD5.byteCount)
try! XCTAssert(Data(Insecure.MD5.hash(data: Data())) == Data(hexString: "d41d8cd98f00b204e9800998ecf8427e"))
try! XCTAssert(Data(Insecure.MD5.hash(data: Data("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".utf8))) == Data(hexString: "8215ef0796a20bcaaae116d3876c664a"))
func testMD5() throws {
XCTAssertEqual(Data(Insecure.MD5.hash(data: Data())).count, Insecure.MD5.byteCount)
XCTAssertEqual(
Data(Insecure.MD5.hash(data: Data())),
try Data(hexString: "d41d8cd98f00b204e9800998ecf8427e")
)
XCTAssertEqual(
Data(Insecure.MD5.hash(data: Data("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq".utf8))),
try Data(hexString: "8215ef0796a20bcaaae116d3876c664a")
)
}
func testHashFunction<H: HashFunction>(hf: H.Type) throws {
let data = ("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu".data(using: String.Encoding.ascii)!)
testHashFunctionWithVector(hf: hf, data: data, testVector: try testVectorForAlgorithm(hashFunction: hf))
testHashFunctionWithVector(hf: hf, data: Data(repeating: 0, count: 0), testVector: try nullTestVectorForAlgorithm(hashFunction: hf))
try orFail { try assertHashFunctionWithVector(hf: hf, data: data, testVector: try testVectorForAlgorithm(hashFunction: hf)) }
try orFail { try assertHashFunctionWithVector(hf: hf, data: Data(repeating: 0, count: 0), testVector: try nullTestVectorForAlgorithm(hashFunction: hf)) }
}
func testHashFunctions() throws {
try testHashFunction(hf: Insecure.SHA1.self)
try testHashFunction(hf: SHA256.self)
try testHashFunction(hf: SHA384.self)
try testHashFunction(hf: SHA512.self)
try orFail { try testHashFunction(hf: Insecure.SHA1.self) }
try orFail { try testHashFunction(hf: SHA256.self) }
try orFail { try testHashFunction(hf: SHA384.self) }
try orFail { try testHashFunction(hf: SHA512.self) }
}
func testHashFunctionImplementsCoW<H: HashFunction>(hf: H.Type) throws {
@@ -100,19 +106,19 @@ class DigestsTests: XCTestCase {
}
func testHashFunctionsImplementCow() throws {
try testHashFunctionImplementsCoW(hf: Insecure.MD5.self)
try testHashFunctionImplementsCoW(hf: Insecure.SHA1.self)
try testHashFunctionImplementsCoW(hf: SHA256.self)
try testHashFunctionImplementsCoW(hf: SHA384.self)
try testHashFunctionImplementsCoW(hf: SHA512.self)
try orFail { try testHashFunctionImplementsCoW(hf: Insecure.MD5.self) }
try orFail { try testHashFunctionImplementsCoW(hf: Insecure.SHA1.self) }
try orFail { try testHashFunctionImplementsCoW(hf: SHA256.self) }
try orFail { try testHashFunctionImplementsCoW(hf: SHA384.self) }
try orFail { try testHashFunctionImplementsCoW(hf: SHA512.self) }
}
func testBlockSizes() {
XCTAssert(Insecure.MD5.blockByteCount == 64)
XCTAssert(Insecure.SHA1.blockByteCount == 64)
XCTAssert(SHA256.blockByteCount == 64)
XCTAssertEqual(Insecure.MD5.blockByteCount, 64)
XCTAssertEqual(Insecure.SHA1.blockByteCount, 64)
XCTAssertEqual(SHA256.blockByteCount, 64)
XCTAssert(SHA384.blockByteCount == 128)
XCTAssert(SHA512.blockByteCount == 128)
XCTAssertEqual(SHA384.blockByteCount, 128)
XCTAssertEqual(SHA512.blockByteCount, 128)
}
}
@@ -25,10 +25,10 @@ import XCTest
#endif
extension NISTECDHTests {
func testGroupOpenSSL<PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement, Curve: OpenSSLSupportedNISTCurve>(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type) {
func padKeyIfNecessary(vector: String, curveDetails: OpenSSLSupportedNISTCurve.Type) -> [UInt8] {
func testGroupOpenSSL<PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement, Curve: OpenSSLSupportedNISTCurve>(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type, file: StaticString = #file, line: UInt = #line) {
func padKeyIfNecessary(vector: String, curveDetails: OpenSSLSupportedNISTCurve.Type, file: StaticString = #file, line: UInt = #line) throws -> [UInt8] {
let hexStringFromVector = (vector.count % 2 == 0) ? vector : "0\(vector)"
return try! Array(hexString: hexStringFromVector)
return try orFail(file: file, line: line) { try Array(hexString: hexStringFromVector) }
}
for testVector in group.tests {
@@ -37,22 +37,23 @@ extension NISTECDHTests {
let publicKey = try PrivKey.PublicKey(derBytes: pkBytes, curve: Curve.self)
var privateBytes = [UInt8]()
privateBytes = padKeyIfNecessary(vector: testVector.privateKey, curveDetails: curve)
privateBytes = try padKeyIfNecessary(vector: testVector.privateKey, curveDetails: curve)
let privateKey = try PrivKey(rawRepresentation: privateBytes)
let result = try privateKey.sharedSecretFromKeyAgreement(with: publicKey as! PrivKey.P)
let agreement = try unwrap(publicKey as? PrivKey.P, file: file, line: line)
let result = try privateKey.sharedSecretFromKeyAgreement(with: agreement)
let expectedResult = try Array(hexString: testVector.shared)
XCTAssertEqual(Array(result.ss), Array(expectedResult))
XCTAssertEqual(Array(result.ss), Array(expectedResult), file: file, line: line)
} catch ECDHTestErrors.PublicKeyFailure {
XCTAssert(testVector.flags.contains("CompressedPoint") || testVector.result == "invalid" || testVector.flags.contains("InvalidPublic") || testVector.flags.contains("InvalidAsn"))
XCTAssert(testVector.flags.contains("CompressedPoint") || testVector.result == "invalid" || testVector.flags.contains("InvalidPublic") || testVector.flags.contains("InvalidAsn"), file: file, line: line)
} catch ECDHTestErrors.ParseSPKIFailure {
XCTAssert(testVector.flags.contains("InvalidAsn") || testVector.flags.contains("UnnamedCurve"))
XCTAssert(testVector.flags.contains("InvalidAsn") || testVector.flags.contains("UnnamedCurve"), file: file, line: line)
} catch {
if testVector.result == "valid" {
XCTAssert(testVector.tcId == 31 || testVector.tcId == 20 || testVector.tcId == 25)
XCTAssert(testVector.tcId == 31 || testVector.tcId == 20 || testVector.tcId == 25, file: file, line: line)
}
}
}
+18 -14
View File
@@ -55,34 +55,38 @@ class X25519Tests: XCTestCase {
let privateKey = Curve25519.KeyAgreement.PrivateKey()
let keyData = privateKey.rawRepresentation
let recoveredKey = try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: keyData)
let recoveredKey = try orFail { try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: keyData) }
let ss1 = try! privateKey.sharedSecretFromKeyAgreement(with: bobsKey.publicKey)
let ss2 = try! recoveredKey.sharedSecretFromKeyAgreement(with: bobsKey.publicKey)
let ss1 = try orFail { try privateKey.sharedSecretFromKeyAgreement(with: bobsKey.publicKey) }
let ss2 = try orFail { try recoveredKey.sharedSecretFromKeyAgreement(with: bobsKey.publicKey) }
XCTAssert(ss1 == ss2)
XCTAssert(recoveredKey.rawRepresentation == keyData)
XCTAssertEqual(ss1, ss2)
XCTAssertEqual(recoveredKey.rawRepresentation, keyData)
}
func testWycheproof() throws {
wycheproofTest(bundleType: self,
jsonName: "x25519_test",
testFunction: { (group: ECDHTestGroup) in
try! testGroup(group: group)
})
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "x25519_test",
testFunction: { (group: ECDHTestGroup) in
try orFail { try testGroup(group: group) }
})
}
}
func testGroup(group: ECDHTestGroup) throws {
for testVector in group.tests {
let publicKey = try! Curve25519.KeyAgreement.PublicKey(rawRepresentation: Array(hexString: testVector.publicKey))
let privateKey = try! Curve25519.KeyAgreement.PrivateKey(rawRepresentation: Array(hexString: testVector.privateKey))
let publicKey = try orFail { try Curve25519.KeyAgreement.PublicKey(rawRepresentation: Array(hexString: testVector.publicKey)) }
let privateKey = try orFail { try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: Array(hexString: testVector.privateKey)) }
do {
let expectedSharedSecret = try Array(hexString: testVector.shared)
XCTAssert(try Array(privateKey.sharedSecretFromKeyAgreement(with: publicKey).ss) == expectedSharedSecret)
let testSharedSecret = try Array(privateKey.sharedSecretFromKeyAgreement(with: publicKey).ss)
XCTAssertEqual(testSharedSecret, expectedSharedSecret)
} catch {
XCTAssert(testVector.result == "invalid")
XCTAssertEqual(testVector.result, "invalid")
}
}
}
+31 -20
View File
@@ -29,7 +29,7 @@ enum ECDHTestErrors: Error {
}
class NISTECDHTests: XCTestCase {
func testInteropFIPSKeys() {
func testInteropFIPSKeys() throws {
var fipsKey: P256.KeyAgreement.PrivateKey = P256.KeyAgreement.PrivateKey(compactRepresentable: false)
for _ in 0...10_000 {
fipsKey = P256.KeyAgreement.PrivateKey(compactRepresentable: false)
@@ -47,30 +47,41 @@ class NISTECDHTests: XCTestCase {
XCTAssertNil(fipsKey.publicKey.compactRepresentation)
XCTAssertNotNil(compactKey.publicKey.compactRepresentation)
let ss1 = try! fipsKey.sharedSecretFromKeyAgreement(with: compactKey.publicKey)
let ss2 = try! compactKey.sharedSecretFromKeyAgreement(with: fipsKey.publicKey)
XCTAssert(ss1 == ss2)
let ss1 = try orFail { try fipsKey.sharedSecretFromKeyAgreement(with: compactKey.publicKey) }
let ss2 = try orFail { try compactKey.sharedSecretFromKeyAgreement(with: fipsKey.publicKey) }
XCTAssertEqual(ss1, ss2)
XCTAssertThrowsError(try P256.KeyAgreement.PublicKey(compactRepresentation: fipsKey.publicKey.rawRepresentation))
XCTAssertNotNil(try P256.KeyAgreement.PublicKey(compactRepresentation: compactKey.publicKey.compactRepresentation!))
let compactRepresentation = try unwrap(compactKey.publicKey.compactRepresentation)
XCTAssertNotNil(try P256.KeyAgreement.PublicKey(compactRepresentation: compactRepresentation))
}
func testWycheproof() throws {
wycheproofTest(bundleType: self,
jsonName: "ecdh_secp256r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P256.KeyAgreement.PrivateKey.self, onCurve: P256.CurveDetails.self)
})
wycheproofTest(bundleType: self,
jsonName: "ecdh_secp384r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P384.KeyAgreement.PrivateKey.self, onCurve: P384.CurveDetails.self)
})
wycheproofTest(bundleType: self,
jsonName: "ecdh_secp521r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P521.KeyAgreement.PrivateKey.self, onCurve: P521.CurveDetails.self)
})
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdh_secp256r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P256.KeyAgreement.PrivateKey.self, onCurve: P256.CurveDetails.self)
})
}
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdh_secp384r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P384.KeyAgreement.PrivateKey.self, onCurve: P384.CurveDetails.self)
})
}
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdh_secp521r1_test",
testFunction: { (group: ECDHTestGroup) in
testGroup(group: group, privateKeys: P521.KeyAgreement.PrivateKey.self, onCurve: P521.CurveDetails.self)
})
}
}
func testGroup<PrivKey: NISTECPrivateKey & DiffieHellmanKeyAgreement, Curve: SupportedCurveDetailsImpl>(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type) {
+7 -7
View File
@@ -23,21 +23,21 @@ import XCTest
#endif
class DERTests: XCTestCase {
func testEncodeDecodeECDSASignature() {
func testEncodeDecodeECDSASignature() throws {
let pointSize = self.coordinateSizeForCurve(P256.CurveDetails.self)
let r = self.randomBytes(count: pointSize)
let s = self.randomBytes(count: pointSize)
let signature = try! P256.Signing.ECDSASignature(rawRepresentation: (r + s))
let signature = try orFail { try P256.Signing.ECDSASignature(rawRepresentation: (r + s)) }
XCTAssert(Data(r + s) == signature.rawRepresentation)
XCTAssertEqual(Data(r + s), signature.rawRepresentation)
let der = try! P256.Signing.ECDSASignature(derRepresentation: signature.derRepresentation)
let der = try orFail { try P256.Signing.ECDSASignature(derRepresentation: signature.derRepresentation) }
XCTAssert(der.rawRepresentation == signature.rawRepresentation)
XCTAssert(der.derRepresentation == signature.derRepresentation)
XCTAssertEqual(der.rawRepresentation, signature.rawRepresentation)
XCTAssertEqual(der.derRepresentation, signature.derRepresentation)
XCTAssert(der.rawRepresentation.count == 64)
XCTAssertEqual(der.rawRepresentation.count, 64)
}
func coordinateSizeForCurve<Curve: SupportedCurveDetailsImpl>(_ curve: Curve.Type) -> Int {
@@ -66,22 +66,22 @@ class HKDFTests: XCTestCase {
}
func testRfcTestVectorsSHA1() throws {
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "rfc-5869-HKDF-SHA1")
let vectors = try decoder.decode([RFCTestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "rfc-5869-HKDF-SHA1") }
let vectors = try orFail { try decoder.decode([RFCTestVector].self) }
for vector in vectors {
precondition(vector.hash == "SHA-1")
try self.testRFCVector(vector, hash: Insecure.SHA1.self)
try orFail { try self.testRFCVector(vector, hash: Insecure.SHA1.self) }
}
}
func testRfcTestVectorsSHA256() throws {
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "rfc-5869-HKDF-SHA256")
let vectors = try decoder.decode([RFCTestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "rfc-5869-HKDF-SHA256") }
let vectors = try orFail { try decoder.decode([RFCTestVector].self) }
for vector in vectors {
precondition(vector.hash == "SHA-256")
try self.testRFCVector(vector, hash: SHA256.self)
try orFail { try self.testRFCVector(vector, hash: SHA256.self) }
}
}
}
@@ -52,41 +52,41 @@ class X963KDFTests: XCTestCase {
func testVectorsSHA1() throws {
// The RFC vector decoder works here too.
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha1")
let vectors = try decoder.decode([TestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha1") }
let vectors = try orFail { try decoder.decode([TestVector].self) }
for vector in vectors {
try self.testVector(vector, hash: Insecure.SHA1.self)
try orFail { try self.testVector(vector, hash: Insecure.SHA1.self) }
}
}
func testRfcTestVectorsSHA256() throws {
// The RFC vector decoder works here too.
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha256")
let vectors = try decoder.decode([TestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha256") }
let vectors = try orFail { try decoder.decode([TestVector].self) }
for vector in vectors {
try self.testVector(vector, hash: SHA256.self)
try orFail { try self.testVector(vector, hash: SHA256.self) }
}
}
func testRfcTestVectorsSHA384() throws {
// The RFC vector decoder works here too.
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha384")
let vectors = try decoder.decode([TestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha384") }
let vectors = try orFail { try decoder.decode([TestVector].self) }
for vector in vectors {
try self.testVector(vector, hash: SHA384.self)
try orFail { try self.testVector(vector, hash: SHA384.self) }
}
}
func testRfcTestVectorsSHA512() throws {
// The RFC vector decoder works here too.
var decoder = try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha512")
let vectors = try decoder.decode([TestVector].self)
var decoder = try orFail { try RFCVectorDecoder(bundleType: self, fileName: "ansx963_2001_sha512") }
let vectors = try orFail { try decoder.decode([TestVector].self) }
for vector in vectors {
try self.testVector(vector, hash: SHA512.self)
try orFail { try self.testVector(vector, hash: SHA512.self) }
}
}
}
+35 -35
View File
@@ -105,74 +105,75 @@ class HMACTests: XCTestCase {
}
}
func testHMAC<H: HashFunction>(key: SymmetricKey, data: Data, vectors: (H.Type) throws -> String, for: H.Type) -> Bool {
return HMAC<H>.isValidAuthenticationCode(try! Data(hexString: vectors(H.self)), authenticating: data, using: key)
func testHMAC<H: HashFunction>(key: SymmetricKey, data: Data, vectors: (H.Type) throws -> String, for: H.Type, file: StaticString = #file, line: UInt = #line) throws -> Bool {
let code = try orFail(file: file, line: line) { try Data(hexString: vectors(H.self)) }
return HMAC<H>.isValidAuthenticationCode(code, authenticating: data, using: key)
}
func testCase1() throws {
let keyBytes = try Array(hexString: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
let keyBytes = try orFail { try Array(hexString: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") }
let key = SymmetricKey(data: keyBytes)
let data = "Hi There".data(using: .ascii)!
XCTAssert(testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase1VectorForAlgorithm, for: SHA512.self))
}
func testCase2() throws {
let keyBytes = try Array(hexString: "4a656665")
let keyBytes = try orFail { try Array(hexString: "4a656665") }
let key = SymmetricKey(data: keyBytes)
let data = try Data(hexString: "7768617420646f2079612077616e7420666f72206e6f7468696e673f")
let data = try orFail { try Data(hexString: "7768617420646f2079612077616e7420666f72206e6f7468696e673f") }
XCTAssert(testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase2VectorForAlgorithm, for: SHA512.self))
}
func testCase3() throws {
let keyBytes = try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }
let key = SymmetricKey(data: keyBytes)
let data = try Data(hexString: "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd")
let data = try orFail { try Data(hexString: "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd") }
XCTAssert(testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase3VectorForAlgorithm, for: SHA512.self))
}
func testCase4() throws {
let keyBytes = try Array(hexString: "0102030405060708090a0b0c0d0e0f10111213141516171819")
let keyBytes = try orFail { try Array(hexString: "0102030405060708090a0b0c0d0e0f10111213141516171819") }
let key = SymmetricKey(data: keyBytes)
let data = try Data(hexString: "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd")
let data = try orFail { try Data(hexString: "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd") }
XCTAssert(testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase4VectorForAlgorithm, for: SHA512.self))
}
func testCase6() throws {
let keyBytes = try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }
let key = SymmetricKey(data: keyBytes)
let data = try Data(hexString: "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a65204b6579202d2048617368204b6579204669727374")
let data = try orFail { try Data(hexString: "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a65204b6579202d2048617368204b6579204669727374") }
XCTAssert(testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase6VectorForAlgorithm, for: SHA512.self))
}
func testCase7() throws {
let keyBytes = try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
let keyBytes = try orFail { try Array(hexString: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") }
let key = SymmetricKey(data: keyBytes)
let data = try Data(hexString: "5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e")
let data = try orFail { try Data(hexString: "5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e") }
XCTAssert(testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA256.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA384.self))
XCTAssert(testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA512.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA256.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA384.self))
XCTAssert(try testHMAC(key: key, data: data, vectors: testCase7VectorForAlgorithm, for: SHA512.self))
}
func testDiscontiguousHMAC<H: HashFunction>(key: SymmetricKey, data: [UInt8], for: H.Type) {
@@ -199,18 +200,17 @@ class HMACTests: XCTestCase {
XCTAssertTrue(authContiguous == discontiguousGoodCode)
XCTAssertFalse(unrelatedAuthenticationCode == contiguousGoodCode)
XCTAssertFalse(unrelatedAuthenticationCode == discontiguousGoodCode)
}
func testDiscontiguousSHA256() throws {
func testDiscontiguousSHA256() {
testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA256.self)
}
func testDiscontiguousSHA384() throws {
func testDiscontiguousSHA384() {
testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA384.self)
}
func testDiscontiguousSHA512() throws {
func testDiscontiguousSHA512() {
testDiscontiguousHMAC(key: SymmetricKey(size: .bits256), data: Array("some data".utf8), for: SHA512.self)
}
@@ -53,51 +53,69 @@ struct EdDSAKey: Codable {
class SignatureTests: XCTestCase {
let data = "Testing Signatures".data(using: String.Encoding.utf8)!
func testWycheProofEdDSA() {
wycheproofTest(bundleType: self,
jsonName: "eddsa_test",
testFunction: { (group: EdDSATestGroup) in
try! testEdGroup(group: group)
})
func testWycheProofEdDSA() throws {
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "eddsa_test",
testFunction: { (group: EdDSATestGroup) in
try orFail { try testEdGroup(group: group) }
})
}
}
func testWycheProofP256() {
wycheproofTest(bundleType: self,
jsonName: "ecdsa_secp256r1_sha256_test",
testFunction: { (group: ECDSATestGroup) in
try! testGroup(group: group, curve: P256.Signing.self, hashFunction: SHA256.self)
})
func testWycheProofP256() throws {
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdsa_secp256r1_sha256_test",
testFunction: { (group: ECDSATestGroup) in
try orFail { try testGroup(group: group, curve: P256.Signing.self, hashFunction: SHA256.self) }
})
}
wycheproofTest(bundleType: self,
jsonName: "ecdsa_secp256r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try! testGroup(group: group, curve: P256.Signing.self, hashFunction: SHA512.self)
})
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdsa_secp256r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try orFail { try testGroup(group: group, curve: P256.Signing.self, hashFunction: SHA512.self) }
})
}
}
func testWycheProofP384() {
wycheproofTest(bundleType: self,
jsonName: "ecdsa_secp384r1_sha384_test",
testFunction: { (group: ECDSATestGroup) in
try! testGroup(group: group, curve: P384.Signing.self, hashFunction: SHA384.self)
})
wycheproofTest(bundleType: self,
jsonName: "ecdsa_secp384r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try! testGroup(group: group, curve: P384.Signing.self, hashFunction: SHA512.self)
})
func testWycheProofP384() throws {
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdsa_secp384r1_sha384_test",
testFunction: { (group: ECDSATestGroup) in
try orFail { try testGroup(group: group, curve: P384.Signing.self, hashFunction: SHA384.self) }
})
}
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdsa_secp384r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try orFail { try testGroup(group: group, curve: P384.Signing.self, hashFunction: SHA512.self) }
})
}
}
func testWycheProofP521() {
wycheproofTest(bundleType: self,
jsonName: "ecdsa_secp521r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try! testGroup(group: group, curve: P521.Signing.self, hashFunction: SHA512.self)
})
func testWycheProofP521() throws {
try orFail {
try wycheproofTest(
bundleType: self,
jsonName: "ecdsa_secp521r1_sha512_test",
testFunction: { (group: ECDSATestGroup) in
try orFail { try testGroup(group: group, curve: P521.Signing.self, hashFunction: SHA512.self) }
})
}
}
func testEdGroup(group: EdDSATestGroup) throws {
let keyBytes = try! Array(hexString: group.key.pk)
let key = try! Curve25519.Signing.PublicKey(rawRepresentation: keyBytes)
func testEdGroup(group: EdDSATestGroup, file: StaticString = #file, line: UInt = #line) throws {
let keyBytes = try orFail { try Array(hexString: group.key.pk) }
let key = try orFail { try Curve25519.Signing.PublicKey(rawRepresentation: keyBytes) }
for testVector in group.tests {
var isValid = false
@@ -125,14 +143,14 @@ class SignatureTests: XCTestCase {
}
case "invalid": XCTAssert(!isValid, "Test ID: \(testVector.tcId) is valid, but failed.")
default:
XCTAssert(false, "Unhandled test vector")
XCTFail("Unhandled test vector")
}
}
}
func testGroup<C: NISTSigning, HF: HashFunction>(group: ECDSATestGroup, curve: C.Type, hashFunction: HF.Type) throws where C.ECDSASignature == C.PublicKey.Signature {
let keyBytes = try! Array(hexString: group.key.uncompressed)
let key = try! C.PublicKey(x963Representation: keyBytes)
func testGroup<C: NISTSigning, HF: HashFunction>(group: ECDSATestGroup, curve: C.Type, hashFunction: HF.Type, file: StaticString = #file, line: UInt = #line) throws where C.ECDSASignature == C.PublicKey.Signature {
let keyBytes = try orFail(file: file, line: line) { try Array(hexString: group.key.uncompressed) }
let key = try orFail(file: file, line: line) { try C.PublicKey(x963Representation: keyBytes) }
for testVector in group.tests {
if testVector.msg == "" {
@@ -151,18 +169,18 @@ class SignatureTests: XCTestCase {
isValid = key.isValidSignature(signature, for: digest)
} catch {
XCTAssert(testVector.result == "invalid" || testVector.result == "acceptable", "Test ID: \(testVector.tcId) is valid, but failed \(error.localizedDescription).")
XCTAssert(testVector.result == "invalid" || testVector.result == "acceptable", "Test ID: \(testVector.tcId) is valid, but failed \(error.localizedDescription).", file: file, line: line)
continue
}
switch testVector.result {
case "valid": XCTAssert(isValid, "Test vector is valid, but is rejected \(testVector.tcId)")
case "valid": XCTAssert(isValid, "Test vector is valid, but is rejected \(testVector.tcId)", file: file, line: line)
case "acceptable": do {
XCTAssert(isValid)
XCTAssert(isValid, file: file, line: line)
}
case "invalid": XCTAssert(!isValid, "Test ID: \(testVector.tcId) is valid, but failed.")
case "invalid": XCTAssert(!isValid, "Test ID: \(testVector.tcId) is valid, but failed.", file: file, line: line)
default:
XCTAssert(false, "Unhandled test vector")
XCTFail("Unhandled test vector", file: file, line: line)
}
}
}
@@ -170,44 +188,44 @@ class SignatureTests: XCTestCase {
func testP256Usage() throws {
let signingKey = P256.Signing.PrivateKey()
let signature = try signingKey.signature(for: data)
let signature = try orFail { try signingKey.signature(for: data) }
XCTAssert(signingKey.publicKey.isValidSignature(signature, for: data))
}
func testP256Representations() throws {
let signingKey = P256.Signing.PrivateKey()
let signature = try signingKey.signature(for: data)
let signature = try orFail { try signingKey.signature(for: data) }
XCTAssertEqual(signature.composite.r + signature.composite.s, signature.rawRepresentation)
let signatureBytesFromPointer = signature.withUnsafeBytes { Data($0) }
XCTAssertEqual(signature.rawRepresentation, signatureBytesFromPointer)
let roundTrippedSignature = try P256.Signing.ECDSASignature(derRepresentation: signature.derRepresentation)
let roundTrippedSignature = try orFail { try P256.Signing.ECDSASignature(derRepresentation: signature.derRepresentation) }
XCTAssertEqual(signature.rawRepresentation, roundTrippedSignature.rawRepresentation)
}
func testP384Representations() throws {
let signingKey = P384.Signing.PrivateKey()
let signature = try signingKey.signature(for: data)
let signature = try orFail { try signingKey.signature(for: data) }
XCTAssertEqual(signature.composite.r + signature.composite.s, signature.rawRepresentation)
let signatureBytesFromPointer = signature.withUnsafeBytes { Data($0) }
XCTAssertEqual(signature.rawRepresentation, signatureBytesFromPointer)
let roundTrippedSignature = try P384.Signing.ECDSASignature(derRepresentation: signature.derRepresentation)
let roundTrippedSignature = try orFail { try P384.Signing.ECDSASignature(derRepresentation: signature.derRepresentation) }
XCTAssertEqual(signature.rawRepresentation, roundTrippedSignature.rawRepresentation)
}
func testP521Representations() throws {
let signingKey = P521.Signing.PrivateKey()
let signature = try signingKey.signature(for: data)
let signature = try orFail { try signingKey.signature(for: data) }
XCTAssertEqual(signature.composite.r + signature.composite.s, signature.rawRepresentation)
let signatureBytesFromPointer = signature.withUnsafeBytes { Data($0) }
XCTAssertEqual(signature.rawRepresentation, signatureBytesFromPointer)
let roundTrippedSignature = try P521.Signing.ECDSASignature(derRepresentation: signature.derRepresentation)
let roundTrippedSignature = try orFail { try P521.Signing.ECDSASignature(derRepresentation: signature.derRepresentation) }
XCTAssertEqual(signature.rawRepresentation, roundTrippedSignature.rawRepresentation)
}
@@ -240,8 +258,8 @@ class SignatureTests: XCTestCase {
// We generate 4 signatures here, all of which should be identical. We validate them all, which means there is a lot of validating here:
// 8 in total.
let (contiguousData, discontiguousData) = Array(data).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols()
let (contiguousDiscontiguous, discontiguousDiscontiguous) = Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = try orFail { Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols() }
let (contiguousDiscontiguous, discontiguousDiscontiguous) = try orFail { Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols() }
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: contiguousContiguous), for: contiguousData))
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: discontiguousContiguous), for: contiguousData))
@@ -270,8 +288,8 @@ class SignatureTests: XCTestCase {
// We generate 4 signatures here, all of which should be identical. We validate them all, which means there is a lot of validating here:
// 8 in total.
let (contiguousData, discontiguousData) = Array(data).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols()
let (contiguousDiscontiguous, discontiguousDiscontiguous) = Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = try orFail { Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols() }
let (contiguousDiscontiguous, discontiguousDiscontiguous) = try orFail { Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols() }
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: contiguousContiguous), for: contiguousData))
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: discontiguousContiguous), for: contiguousData))
@@ -300,8 +318,8 @@ class SignatureTests: XCTestCase {
// We generate 4 signatures here, all of which should be identical. We validate them all, which means there is a lot of validating here:
// 8 in total.
let (contiguousData, discontiguousData) = Array(data).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols()
let (contiguousDiscontiguous, discontiguousDiscontiguous) = Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols()
let (contiguousContiguous, discontiguousContiguous) = try orFail { Array(try signingKey.signature(for: contiguousData).derRepresentation).asDataProtocols() }
let (contiguousDiscontiguous, discontiguousDiscontiguous) = try orFail { Array(try signingKey.signature(for: discontiguousData).derRepresentation).asDataProtocols() }
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: contiguousContiguous), for: contiguousData))
XCTAssertTrue(signingKey.publicKey.isValidSignature(try .init(derRepresentation: discontiguousContiguous), for: contiguousData))
@@ -25,26 +25,29 @@ import XCTest
typealias TestVector = (publicKey: Data, privateKey: Data, rs: rAndS)
typealias rAndS = (r: Data, s: Data)
func testVectorForCurve<S: NISTSigning>(curve: S.Type) throws -> TestVector {
func testVectorForCurve<S: NISTSigning>(curve: S.Type, file: StaticString = #file, line: UInt = #line) throws -> TestVector {
switch S.self {
case is P256.Signing.Type:
do {
return TestVector(publicKey: try Data(hexString: "2442a5cc0ecd015fa3ca31dc8e2bbc70bf42d60cbca20085e0822cb04235e9706fc98bd7e50211a4a27102fa3549df79ebcb4bf246b80945cddfe7d509bbfd7d"),
privateKey: try Data(hexString: "dc51d3866a15bacde33d96f992fca99da7e6ef0934e7097559c27f1614c88a7f"),
rs: rAndS(r: try Data(hexString: "cb28e0999b9c7715fd0a80d8e47a77079716cbbf917dd72e97566ea1c066957c"),
s: try Data(hexString: "86fa3bb4e26cad5bf90b7f81899256ce7594bb1ea0c89212748bff3b3d5b0315")))
return TestVector(
publicKey: try orFail(file: file, line: line) { try Data(hexString: "2442a5cc0ecd015fa3ca31dc8e2bbc70bf42d60cbca20085e0822cb04235e9706fc98bd7e50211a4a27102fa3549df79ebcb4bf246b80945cddfe7d509bbfd7d") },
privateKey: try orFail(file: file, line: line) { try Data(hexString: "dc51d3866a15bacde33d96f992fca99da7e6ef0934e7097559c27f1614c88a7f") },
rs: rAndS(r: try orFail(file: file, line: line) { try Data(hexString: "cb28e0999b9c7715fd0a80d8e47a77079716cbbf917dd72e97566ea1c066957c") },
s: try orFail(file: file, line: line) { try Data(hexString: "86fa3bb4e26cad5bf90b7f81899256ce7594bb1ea0c89212748bff3b3d5b0315") }))
}
case is P384.Signing.Type: do {
return TestVector(publicKey: try Data(hexString: "96281bf8dd5e0525ca049c048d345d3082968d10fedf5c5aca0c64e6465a97ea5ce10c9dfec21797415710721f437922447688ba94708eb6e2e4d59f6ab6d7edff9301d249fe49c33096655f5d502fad3d383b91c5e7edaa2b714cc99d5743ca"),
privateKey: try Data(hexString: "0beb646634ba87735d77ae4809a0ebea865535de4c1e1dcb692e84708e81a5af62e528c38b2a81b35309668d73524d9f"),
rs: rAndS(r: try Data(hexString: "fb017b914e29149432d8bac29a514640b46f53ddab2c69948084e2930f1c8f7e08e07c9c63f2d21a07dcb56a6af56eb3"),
s: try Data(hexString: "b263a1305e057f984d38726a1b46874109f417bca112674c528262a40a629af1cbb9f516ce0fa7d2ff630863a00e8b9f")))
return TestVector(
publicKey: try orFail(file: file, line: line) { try Data(hexString: "96281bf8dd5e0525ca049c048d345d3082968d10fedf5c5aca0c64e6465a97ea5ce10c9dfec21797415710721f437922447688ba94708eb6e2e4d59f6ab6d7edff9301d249fe49c33096655f5d502fad3d383b91c5e7edaa2b714cc99d5743ca") },
privateKey: try orFail(file: file, line: line) { try Data(hexString: "0beb646634ba87735d77ae4809a0ebea865535de4c1e1dcb692e84708e81a5af62e528c38b2a81b35309668d73524d9f") },
rs: rAndS(r: try orFail(file: file, line: line) { try Data(hexString: "fb017b914e29149432d8bac29a514640b46f53ddab2c69948084e2930f1c8f7e08e07c9c63f2d21a07dcb56a6af56eb3") },
s: try orFail(file: file, line: line) { try Data(hexString: "b263a1305e057f984d38726a1b46874109f417bca112674c528262a40a629af1cbb9f516ce0fa7d2ff630863a00e8b9f") }))
}
case is P521.Signing.Type: do {
return TestVector(publicKey: try Data(hexString: "0151518f1af0f563517edd5485190df95a4bf57b5cba4cf2a9a3f6474725a35f7afe0a6ddeb8bedbcd6a197e592d40188901cecd650699c9b5e456aea5add19052a8006f3b142ea1bfff7e2837ad44c9e4ff6d2d34c73184bbad90026dd5e6e85317d9df45cad7803c6c20035b2f3ff63aff4e1ba64d1c077577da3f4286c58f0aeae643"),
privateKey: try Data(hexString: "0065fda3409451dcab0a0ead45495112a3d813c17bfd34bdf8c1209d7df5849120597779060a7ff9d704adf78b570ffad6f062e95c7e0c5d5481c5b153b48b375fa1"),
rs: rAndS(r: try Data(hexString: "0154fd3836af92d0dca57dd5341d3053988534fde8318fc6aaaab68e2e6f4339b19f2f281a7e0b22c269d93cf8794a9278880ed7dbb8d9362caeacee544320552251"),
s: try Data(hexString: "017705a7030290d1ceb605a9a1bb03ff9cdd521e87a696ec926c8c10c8362df4975367101f67d1cf9bccbf2f3d239534fa509e70aac851ae01aac68d62f866472660")))
return TestVector(
publicKey: try orFail(file: file, line: line) { try Data(hexString: "0151518f1af0f563517edd5485190df95a4bf57b5cba4cf2a9a3f6474725a35f7afe0a6ddeb8bedbcd6a197e592d40188901cecd650699c9b5e456aea5add19052a8006f3b142ea1bfff7e2837ad44c9e4ff6d2d34c73184bbad90026dd5e6e85317d9df45cad7803c6c20035b2f3ff63aff4e1ba64d1c077577da3f4286c58f0aeae643") },
privateKey: try orFail(file: file, line: line) { try Data(hexString: "0065fda3409451dcab0a0ead45495112a3d813c17bfd34bdf8c1209d7df5849120597779060a7ff9d704adf78b570ffad6f062e95c7e0c5d5481c5b153b48b375fa1") },
rs: rAndS(r: try orFail(file: file, line: line) { try Data(hexString: "0154fd3836af92d0dca57dd5341d3053988534fde8318fc6aaaab68e2e6f4339b19f2f281a7e0b22c269d93cf8794a9278880ed7dbb8d9362caeacee544320552251") },
s: try orFail(file: file, line: line) { try Data(hexString: "017705a7030290d1ceb605a9a1bb03ff9cdd521e87a696ec926c8c10c8362df4975367101f67d1cf9bccbf2f3d239534fa509e70aac851ae01aac68d62f866472660") }))
}
default:
XCTFail("Unhandled type: \(S.self)")
@@ -53,31 +56,34 @@ func testVectorForCurve<S: NISTSigning>(curve: S.Type) throws -> TestVector {
}
class RawECDSASignaturesTests: XCTestCase {
func testForCurve<S: NISTSigning>(curve: S.Type) {
let msg = "abc".data(using: .utf8)!
func testForCurve<S: NISTSigning>(curve: S.Type, file: StaticString = #file, line: UInt = #line) throws {
let msg = try unwrap("abc".data(using: .utf8), file: file, line: line)
// We check that the test message is correctly encoded.
try XCTAssert(msg == Data(hexString: "616263"))
XCTAssertEqual(msg, try Data(hexString: "616263"), file: file, line: line)
let tv = try! testVectorForCurve(curve: curve)
let tv = try orFail(file: file, line: line) { try testVectorForCurve(curve: curve) }
let signature = try! S.ECDSASignature(rawRepresentation: tv.rs.r + tv.rs.s)
let signature = try orFail(file: file, line: line) { try S.ECDSASignature(rawRepresentation: tv.rs.r + tv.rs.s) }
let privateKey = try! S.PrivateKey(rawRepresentation: tv.privateKey)
let publicKey = try! S.PublicKey(rawRepresentation: tv.publicKey)
let privateKey = try orFail(file: file, line: line) { try S.PrivateKey(rawRepresentation: tv.privateKey) }
let publicKey = try orFail(file: file, line: line) { try S.PublicKey(rawRepresentation: tv.publicKey) }
XCTAssert(privateKey.rawRepresentation == tv.privateKey)
XCTAssert(privateKey.publicKey.rawRepresentation == tv.publicKey)
XCTAssert(publicKey.isValidSignature(signature as! S.PublicKey.Signature, for: msg))
XCTAssertEqual(privateKey.rawRepresentation, tv.privateKey, file: file, line: line)
XCTAssertEqual(privateKey.publicKey.rawRepresentation, tv.publicKey, file: file, line: line)
XCTAssert(publicKey.isValidSignature(try privateKey.signature(for: msg) as! S.PublicKey.Signature, for: msg))
let typedSignature = try unwrap(signature as? S.PublicKey.Signature, file: file, line: line)
XCTAssert(publicKey.isValidSignature(typedSignature, for: msg), file: file, line: line)
let privateKeySignature = try orFail { try privateKey.signature(for: msg) }
let typedPrivateKeySignature = try unwrap(privateKeySignature as? S.PublicKey.Signature, file: file, line: line)
XCTAssert(publicKey.isValidSignature(typedPrivateKeySignature, for: msg), file: file, line: line)
}
// Test Vectors from: https://tools.ietf.org/html/rfc4754#section-8
func testRFC4753() throws {
testForCurve(curve: P256.Signing.self)
testForCurve(curve: P384.Signing.self)
testForCurve(curve: P521.Signing.self)
try orFail { try testForCurve(curve: P256.Signing.self) }
try orFail { try testForCurve(curve: P384.Signing.self) }
try orFail { try testForCurve(curve: P521.Signing.self) }
}
}
#endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM
@@ -28,7 +28,7 @@ class EdDSATests: XCTestCase {
let someData = "Some Data".data(using: .utf8)!
let signature = try privateKey.signature(for: someData)
let signature = try orFail { try privateKey.signature(for: someData) }
XCTAssert(publicKey.isValidSignature(signature, for: someData))
}
@@ -37,8 +37,8 @@ class EdDSATests: XCTestCase {
let privateKey = Curve25519.Signing.PrivateKey()
let (someContiguousData, someDiscontiguousData) = Array("Some Data".utf8).asDataProtocols()
let signatureOnContiguous = try privateKey.signature(for: someContiguousData)
let signatureOnDiscontiguous = try privateKey.signature(for: someDiscontiguousData)
let signatureOnContiguous = try orFail { try privateKey.signature(for: someContiguousData) }
let signatureOnDiscontiguous = try orFail { try privateKey.signature(for: someDiscontiguousData) }
#if !(os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
XCTAssertEqual(signatureOnContiguous, signatureOnDiscontiguous)
#endif
@@ -56,7 +56,7 @@ class EdDSATests: XCTestCase {
let otherPrivateKey = Curve25519.Signing.PrivateKey()
let (someContiguousData, someDiscontiguousData) = Array("Some Data".utf8).asDataProtocols()
let signature = try privateKey.signature(for: someContiguousData)
let signature = try orFail { try privateKey.signature(for: someContiguousData) }
// This tests the 4 combinations.
let (contiguousSignature, discontiguousSignature) = Array(signature).asDataProtocols()
@@ -68,11 +68,11 @@ class EdDSATests: XCTestCase {
func testSigningZeroRegionDataProtocol() throws {
let privateKey = Curve25519.Signing.PrivateKey()
let signature = try privateKey.signature(for: DispatchData.empty)
let signature = try orFail { try privateKey.signature(for: DispatchData.empty) }
XCTAssert(privateKey.publicKey.isValidSignature(signature, for: DispatchData.empty))
// This should fail
// This signature should be invalid
XCTAssertFalse(privateKey.publicKey.isValidSignature(DispatchData.empty, for: DispatchData.empty))
}
}
+2 -2
View File
@@ -39,8 +39,8 @@ private func htoi(_ value: UInt8) throws -> UInt8 {
extension Array where Element == UInt8 {
init(hexString: String) throws {
self.init()
if hexString.count % 2 != 0 || hexString.count == 0 {
guard hexString.count.isMultiple(of: 2), !hexString.isEmpty else {
throw ByteHexEncodingErrors.incorrectString
}
+16 -14
View File
@@ -11,7 +11,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Foundation
import XCTest
struct WycheproofTest<T: Codable>: Codable {
let algorithm: String
@@ -19,21 +19,23 @@ struct WycheproofTest<T: Codable>: Codable {
let testGroups: [T]
}
func wycheproofTest<T: Codable>(bundleType: AnyObject, jsonName: String, testFunction: (T) -> Void) {
#if !CRYPTO_IN_SWIFTPM
let bundle = Bundle(for: type(of: bundleType))
let fileURL = bundle.url(forResource: jsonName, withExtension: "json")
#else
let testsDirectory: String = URL(fileURLWithPath: "\(#file)").pathComponents.dropLast(3).joined(separator: "/")
let fileURL: URL? = URL(fileURLWithPath: "\(testsDirectory)/Test Vectors/\(jsonName).json")
#endif
extension XCTestCase {
func wycheproofTest<T: Codable>(bundleType: AnyObject, jsonName: String, file: StaticString = #file, line: UInt = #line, testFunction: (T) throws -> Void) throws {
#if !CRYPTO_IN_SWIFTPM
let bundle = Bundle(for: type(of: bundleType))
let fileURL = bundle.url(forResource: jsonName, withExtension: "json")
#else
let testsDirectory: String = URL(fileURLWithPath: "\(#file)").pathComponents.dropLast(3).joined(separator: "/")
let fileURL: URL? = URL(fileURLWithPath: "\(testsDirectory)/Test Vectors/\(jsonName).json")
#endif
let data = try! Data(contentsOf: fileURL!)
let data = try orFail(file: file, line: line) { try Data(contentsOf: unwrap(fileURL, file: file, line: line)) }
let decoder = JSONDecoder()
let wpTest = try! decoder.decode(WycheproofTest<T>.self, from: data)
let decoder = JSONDecoder()
let wpTest = try orFail(file: file, line: line) { try decoder.decode(WycheproofTest<T>.self, from: data) }
for group in wpTest.testGroups {
testFunction(group)
for group in wpTest.testGroups {
try orFail(file: file, line: line) { try testFunction(group) }
}
}
}
+61
View File
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
// Xcode 11.4 catches errors thrown during tests and reports them on the
// correct line. But Linux and older Xcodes do not, so we need to use this
// wrapper as long as those platforms are supported.
func orFail<T>(file: StaticString = #file, line: UInt = #line, _ closure: () throws -> T) throws -> T {
func wrapper<T>(_ closure: () throws -> T, file: StaticString, line: UInt) throws -> T {
do {
return try closure()
} catch {
XCTFail("Function threw error: \(error)", file: file, line: line)
throw error
}
}
#if compiler(>=5.2) && canImport(Darwin)
if #available(macOS 10.15.4, macCatalyst 13.4, iOS 13.4, tvOS 13.4, watchOS 6.0, *) {
return try closure()
} else {
return try wrapper(closure, file: file, line: line)
}
#else
return try wrapper(closure, file: file, line: line)
#endif
}
extension XCTestCase {
struct OptionalUnwrappingError: Error {
let file: StaticString
let line: UInt
}
/// Unwraps the given optional value, or if it is nil, throws an error and
/// registers an XCTest failure. Meant to be used in a test method that has
/// been marked as `throws`.
/// - Note: this is a replacement for `XCTUnwrap`, which is not availble
/// in SPM command line builds as of this writing: <https://bugs.swift.org/browse/SR-11501>
func unwrap<T>(_ optional: T?, file: StaticString = #file, line: UInt = #line) throws -> T {
guard let wrapped = optional else {
XCTFail("Optional was nil", file: file, line: line)
throw OptionalUnwrappingError(file: file, line: line)
}
return wrapped
}
}