Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Source/AwsCommonRuntimeKit/crt/EC.swift
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,44 @@ public class ECKeyPair {
}
}

/// Decode der ec signature into padded R || S
/// both R and S are first padded and then concatenated
static public func decodeDerEcSignatureToPaddedPair(signature: Data, padTo: Int) throws -> Data {

return try signature.withUnsafeBytes { signaturePointer -> Data in
let signatureCur = aws_byte_cursor_from_array(
signaturePointer.baseAddress,
signature.count
)

if padTo > 256 {
throw CommonRunTimeError.crtError(CRTError(code: AWS_ERROR_INVALID_ARGUMENT.rawValue))
}

let bufferSize = padTo * 2
var outData = Data(count: bufferSize)
var newBufferSize = 0

try outData.withUnsafeMutableBytes { outPointer in
var outBuf = aws_byte_buf_from_empty_array(outPointer.baseAddress, bufferSize)
guard
aws_ecc_decode_signature_der_to_raw_padded(
allocator.rawValue,
signatureCur,
&outBuf,
padTo
) == AWS_OP_SUCCESS
else {
throw CommonRunTimeError.crtError(.makeFromLastError())
}
newBufferSize = outBuf.len
}

outData.count = newBufferSize
return outData
}
}

/// Encode raw ec signature into der format
static public func encodeRawECSignature(signature: ECKeyPair.ECRawSignature) throws -> Data {
return try signature.r.withUnsafeBytes { rPointer in
Expand Down
26 changes: 26 additions & 0 deletions Test/AwsCommonRuntimeKitTests/crt/ECTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,30 @@ class ECTests: XCBaseTestCase {
XCTAssertTrue(ecKey.verify(digest: sha256, signature: signature))
}

func testDecodePadded() throws {

let signature: [UInt8] = [
0x30, 0x42, 0x02, 0x1f, 0x2d, 0x2a, 0xad, 0xce, 0xbc, 0x1b, 0x3f, 0x78,
0xec, 0xd1, 0x12, 0x53, 0x9e, 0xc0, 0xe3, 0x44, 0x7b, 0x37, 0x5f, 0x6a,
0x99, 0xca, 0x0b, 0x27, 0xb5, 0x4c, 0x31, 0xda, 0x0e, 0x6c, 0x5e, 0x02,
0x1f, 0x47, 0xfb, 0x3d, 0xbd, 0xff, 0xb8, 0x58, 0xf4, 0xba, 0x8a, 0x03,
0xe7, 0xb4, 0x83, 0xe6, 0xb8, 0xc9, 0x46, 0xa8, 0x0a, 0xd8, 0x46, 0xfa,
0x80, 0x0a, 0xd8, 0xca, 0xc5, 0x3f, 0x8e, 0xbd,
]
let signatureData = Data(_: signature)

let expected: [UInt8] = [
0x00, 0x2d, 0x2a, 0xad, 0xce, 0xbc, 0x1b, 0x3f, 0x78, 0xec, 0xd1, 0x12, 0x53,
0x9e, 0xc0, 0xe3, 0x44, 0x7b, 0x37, 0x5f, 0x6a, 0x99, 0xca, 0x0b, 0x27, 0xb5,
0x4c, 0x31, 0xda, 0x0e, 0x6c, 0x5e, 0x00, 0x47, 0xfb, 0x3d, 0xbd, 0xff, 0xb8,
0x58, 0xf4, 0xba, 0x8a, 0x03, 0xe7, 0xb4, 0x83, 0xe6, 0xb8, 0xc9, 0x46, 0xa8,
0x0a, 0xd8, 0x46, 0xfa, 0x80, 0x0a, 0xd8, 0xca, 0xc5, 0x3f, 0x8e, 0xbd,
]
let expectedData = Data(_: expected)

let raw = try ECKeyPair.decodeDerEcSignatureToPaddedPair(signature: signatureData, padTo: 32)

XCTAssertEqual(expectedData, raw)
}

}
Loading