Support compressed keys. (#87)

Motivation:

CryptoKit supports the compressed key format: we should as well.

Modifications:

Extend the constructors of public keys to tolerate the compressed
representation.

Result:

Users holding compressed keys can use them.
This commit is contained in:
Cory Benfield authored and GitHub committed 2021-07-30 07:20:33 +01:00
1 parent 22fd389195
commit 53da7b3706
5 files changed
+157 -5

No files matched your search

@@ -51,6 +51,15 @@ extension BoringSSLEllipticCurveGroup {
return key
}
@usableFromInline
func makeUnsafeOwnedECPoint() throws -> OpaquePointer {
guard let point = CCryptoBoringSSL_EC_POINT_new(self._group) else {
throw CryptoKitError.internalBoringSSLError()
}
return point
}
@inlinable
func withUnsafeGroupPointer<T>(_ body: (OpaquePointer) throws -> T) rethrows -> T {
try body(self._group)
@@ -363,13 +363,21 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
// This brings our behaviour into line with CryptoKit
let group = Curve.group
let length = bytes.withUnsafeBytes { $0.count }
guard length == (group.coordinateByteCount * 2) + 1 else {
switch length {
case (group.coordinateByteCount * 2) + 1:
var (x, y) = try bytes.readx963PublicNumbers()
self.key = try group.makeUnsafeOwnedECKey()
try self.setPublicKey(x: &x, y: &y)
case group.coordinateByteCount + 1:
var (x, yBit) = try bytes.readx963CompressedPublicNumbers()
self.key = try group.makeUnsafeOwnedECKey()
try self.setPublicKey(x: &x, yBit: yBit)
default:
throw CryptoKitError.incorrectParameterSize
}
self.key = try group.makeUnsafeOwnedECKey()
var (x, y) = try bytes.readx963PublicNumbers()
try self.setPublicKey(x: &x, y: &y)
}
init<Bytes: ContiguousBytes>(rawRepresentation bytes: Bytes) throws {
@@ -473,6 +481,29 @@ class BoringSSLECPublicKeyWrapper<Curve: OpenSSLSupportedNISTCurve> {
}
}
func setPublicKey(x: inout ArbitraryPrecisionInteger, yBit: Bool) throws {
try x.withUnsafeMutableBignumPointer { xPointer in
// We cannot handle allocation errors.
let point = try Curve.group.makeUnsafeOwnedECPoint()
defer {
// We either error, or EC_KEY_set_public_key dups the key,
// so we must always free.
CCryptoBoringSSL_EC_POINT_free(point)
}
let rc = Curve.group.withUnsafeGroupPointer { groupPtr in
CCryptoBoringSSL_EC_POINT_set_compressed_coordinates_GFp(groupPtr, point, xPointer, yBit ? 1 : 0, nil)
}
guard rc == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
guard CCryptoBoringSSL_EC_KEY_set_public_key(self.key, point) == 1 else {
throw CryptoKitError.internalBoringSSLError()
}
}
}
func isValidSignature<D: Digest>(_ signature: ECDSASignature, for digest: D) -> Bool {
let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in
digest.withUnsafeBytes { digestPointer in
@@ -521,6 +552,29 @@ extension ContiguousBytes {
return try readRawPublicNumbers(copyingBytes: UnsafeRawBufferPointer(rebasing: bytesPtr[1...]))
}
}
@inlinable
func readx963CompressedPublicNumbers() throws -> (x: ArbitraryPrecisionInteger, yBit: Bool) {
// The x9.63 compressed public key format is a discriminator byte (0x2 or 0x3) that signals which
// of the possible two Y values is being used, concatenated with the X point of the key.
return try self.withUnsafeBytes { bytesPtr in
let yBit: Bool
switch bytesPtr.first {
case 0x03:
yBit = true
case 0x02:
yBit = false
default:
throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms.
}
let xBytes = UnsafeRawBufferPointer(rebasing: bytesPtr.dropFirst())
let x = try ArbitraryPrecisionInteger(bytes: xBytes)
return (x: x, yBit: yBit)
}
}
}
@usableFromInline
@@ -88,6 +88,7 @@ extension ArbitraryPrecisionInteger {
// MARK: - Extra initializers
extension ArbitraryPrecisionInteger {
@usableFromInline
init<Bytes: ContiguousBytes>(bytes: Bytes) throws {
self._backing = try BackingStorage(bytes: bytes)
}
@@ -63,6 +63,50 @@ class X25519Tests: XCTestCase {
XCTAssertEqual(ss1, ss2)
XCTAssertEqual(recoveredKey.rawRepresentation, keyData)
}
func testCompressedKeys() throws {
let x963Positive = Data(base64Encoded: "A+QHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L")!
let key = try P256.KeyAgreement.PublicKey(x963Representation: x963Positive)
XCTAssertEqual(
key.x963Representation.base64EncodedString(),
"BOQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7LE6xvfFkB4Y3VXoOpB/Kp6ngpf3Lce9hDMl7fqaDUfYE="
)
let x963Negative = Data(base64Encoded: "AuQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L")!
let negativeKey = try P256.KeyAgreement.PublicKey(x963Representation: x963Negative)
XCTAssertEqual(
negativeKey.x963Representation.base64EncodedString(),
"BOQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L7FOQgqb+HnMqoXxW+A1WFYfWgI4jhCe8zaEgVl8rgn4="
)
let p384Positive = Data(base64Encoded: "AyEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNpw==")!
let p384Key = try P384.KeyAgreement.PublicKey(x963Representation: p384Positive)
XCTAssertEqual(
p384Key.x963Representation.base64EncodedString(),
"BCEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNp22k0ZcxSL1Ljf19pe25Y6UgedrZf1sOLBVVDZxO36mxwUgPUqFp5/0nNmGMDdQeTQ=="
)
let p384Negative = Data(base64Encoded: "AiEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNpw==")!
let p384NegativeKey = try P384.KeyAgreement.PublicKey(x963Representation: p384Negative)
XCTAssertEqual(
p384NegativeKey.x963Representation.base64EncodedString(),
"BCEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNp5JbLmjOt0K0cgKCWhJGnFrfhiUmgKTx0+qq8mOxIFZNPrfwrF6WGALYyZ508ivhsg=="
)
let p521Positive = Data(base64Encoded: "AwGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4Iw==")!
let p521Key = try P521.KeyAgreement.PublicKey(x963Representation: p521Positive)
XCTAssertEqual(
p521Key.x963Representation.base64EncodedString(),
"BAGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4IwE8xEGqskayEkbPkQCGqSKfVYPZTkBdEs1ham1IXcqT4HSfoGGw98UwjQRiDPfIv0+vU6ocPbxURTdvwUSWPm72WQ=="
)
let p521Negative = Data(base64Encoded: "AgGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4Iw==")!
let p521NegativeKey = try P521.KeyAgreement.PublicKey(x963Representation: p521Negative)
XCTAssertEqual(
p521NegativeKey.x963Representation.base64EncodedString(),
"BAGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4IwDDO75VTblN7bkwbv95Vt1gqnwmsb+i7TKelZK3ojVsH4tgX55PCDrPcvud8wg3QLBQrFXjwkOrusiQPrtpwZEJpg=="
)
}
func testWycheproof() throws {
try orFail {
@@ -341,5 +341,49 @@ class SignatureTests: XCTestCase {
XCTAssertFalse(anotherKey.publicKey.isValidSignature(try .init(derRepresentation: contiguousDiscontiguous), for: discontiguousData))
XCTAssertFalse(anotherKey.publicKey.isValidSignature(try .init(derRepresentation: discontiguousDiscontiguous), for: discontiguousData))
}
func testCompressedKeys() throws {
let x963Positive = Data(base64Encoded: "A+QHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L")!
let key = try P256.Signing.PublicKey(x963Representation: x963Positive)
XCTAssertEqual(
key.x963Representation.base64EncodedString(),
"BOQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7LE6xvfFkB4Y3VXoOpB/Kp6ngpf3Lce9hDMl7fqaDUfYE="
)
let x963Negative = Data(base64Encoded: "AuQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L")!
let negativeKey = try P256.Signing.PublicKey(x963Representation: x963Negative)
XCTAssertEqual(
negativeKey.x963Representation.base64EncodedString(),
"BOQHCXtGd5WWSQgp37FBPXMy+nnSwFK79QQD0ZeNMv7L7FOQgqb+HnMqoXxW+A1WFYfWgI4jhCe8zaEgVl8rgn4="
)
let p384Positive = Data(base64Encoded: "AyEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNpw==")!
let p384Key = try P384.Signing.PublicKey(x963Representation: p384Positive)
XCTAssertEqual(
p384Key.x963Representation.base64EncodedString(),
"BCEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNp22k0ZcxSL1Ljf19pe25Y6UgedrZf1sOLBVVDZxO36mxwUgPUqFp5/0nNmGMDdQeTQ=="
)
let p384Negative = Data(base64Encoded: "AiEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNpw==")!
let p384NegativeKey = try P384.Signing.PublicKey(x963Representation: p384Negative)
XCTAssertEqual(
p384NegativeKey.x963Representation.base64EncodedString(),
"BCEfGE5ySReJyfSruLRdsjvCB5RNWGLk8JYrzIrans3MprXf5Q4nh69bQ2rI4+DNp5JbLmjOt0K0cgKCWhJGnFrfhiUmgKTx0+qq8mOxIFZNPrfwrF6WGALYyZ508ivhsg=="
)
let p521Positive = Data(base64Encoded: "AwGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4Iw==")!
let p521Key = try P521.Signing.PublicKey(x963Representation: p521Positive)
XCTAssertEqual(
p521Key.x963Representation.base64EncodedString(),
"BAGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4IwE8xEGqskayEkbPkQCGqSKfVYPZTkBdEs1ham1IXcqT4HSfoGGw98UwjQRiDPfIv0+vU6ocPbxURTdvwUSWPm72WQ=="
)
let p521Negative = Data(base64Encoded: "AgGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4Iw==")!
let p521NegativeKey = try P521.Signing.PublicKey(x963Representation: p521Negative)
XCTAssertEqual(
p521NegativeKey.x963Representation.base64EncodedString(),
"BAGUsatNKbCi6jeO1oFHpvhxesJnRxeZ45/sqCvaEZgwnpyj+/SsXjgBViEjvlJUdqentCaUFCwjuYZJM9HpdVq4IwDDO75VTblN7bkwbv95Vt1gqnwmsb+i7TKelZK3ojVsH4tgX55PCDrPcvud8wg3QLBQrFXjwkOrusiQPrtpwZEJpg=="
)
}
}
#endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM