Skip to content

Commit

Permalink
feat: derive legacy ecdsa
Browse files Browse the repository at this point in the history
Signed-off-by: Ricky Saechao <[email protected]>
  • Loading branch information
RickyLB committed Dec 18, 2024
1 parent 77c8da2 commit 5e6e297
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion Sources/Hedera/PrivateKey.swift
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,25 @@ public struct PrivateKey: LosslessStringConvertible, ExpressibleByStringLiteral,

public func legacyDerive(_ index: Int64) throws -> Self {
switch kind {
case .ecdsa: throw HError(kind: .keyDerive, description: "ecdsa keys are currently underivable")
case .ecdsa(let key):
var seed = key.dataRepresentation

seed.append(contentsOf: index.bigEndianBytes)

let salt = Data([0xff])
let derivedKey = Pkcs5.pbkdf2(
variant: .sha2(.sha512),
password: seed,
salt: salt,
rounds: 2048,
keySize: 32
)

guard let newKey = try? P256.Signing.PrivateKey(rawRepresentation: derivedKey) else {
throw KeyDerivationError.invalidDerivedKey
}

return try .fromBytesEcdsa(newKey.rawRepresentation)

case .ed25519(let key):
var seed = key.rawRepresentation
Expand Down Expand Up @@ -669,6 +687,16 @@ extension UInt32 {
}
}

extension Int64 {
fileprivate var bigEndianBytes: [UInt8] {
withUnsafeBytes(of: self.bigEndian) { Array($0) }
}
}

enum KeyDerivationError: Error {
case invalidDerivedKey
}

#if compiler(>=5.7)
extension PrivateKey.Repr: Sendable {}
#else
Expand Down

0 comments on commit 5e6e297

Please sign in to comment.