Skip to content

Commit e2f4de7

Browse files
authored
Add format conversion function for convenience (#707)
1 parent b3ad72e commit e2f4de7

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

Sources/zkp/Asymmetric.swift

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,24 @@ public extension secp256k1 {
151151
return try Self(dataRepresentation: negatedKey.dataRepresentation, format: negatedKey.format)
152152
}
153153
}
154+
155+
/// Returns a public key in uncompressed 65 byte form
156+
public var uncompressedRepresentation: Data {
157+
let context = secp256k1.Context.rawRepresentation
158+
var pubKey = rawRepresentation
159+
var pubKeyLen = ByteLength.uncompressedPublicKey
160+
var pubKeyBytes = [UInt8](repeating: 0, count: pubKeyLen)
161+
162+
_ = secp256k1_ec_pubkey_serialize(
163+
context,
164+
&pubKeyBytes,
165+
&pubKeyLen,
166+
&pubKey,
167+
UInt32(SECP256K1_EC_UNCOMPRESSED)
168+
)
169+
170+
return Data(pubKeyBytes)
171+
}
154172

155173
/// Generates a secp256k1 public key.
156174
///

Sources/zkp/secp256k1.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ extension secp256k1 {
6464
/// Number of bytes in a secp256k1 signature.
6565
@inlinable
6666
static var partialSignature: Int { 36 }
67+
68+
@inlinable
69+
static var uncompressedPublicKey: Int { 65 }
6770
}
6871
}
6972

Tests/zkpTests/secp256k1Tests.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,6 +648,12 @@ final class secp256k1Tests: XCTestCase, @unchecked Sendable {
648648

649649
XCTAssertEqual(combinedKeyBytes, expectedCombinedKey)
650650
}
651+
652+
func testKeyFormatConversion() throws {
653+
let pubkey = try secp256k1.Signing.PublicKey(dataRepresentation: "02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2".bytes, format: .compressed)
654+
let uncompressed = pubkey.uncompressedRepresentation
655+
XCTAssertEqual(String(bytes: uncompressed.bytes), "04a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba270b2031fef3acf8e13ea7a395e375491bdc37be1cd79e073d82bfd5ba8d35d68")
656+
}
651657

652658
func testPrivateKeyPEM() {
653659
let privateKeyString = """

0 commit comments

Comments
 (0)