Skip to content

Commit 737c445

Browse files
authored
feat: expose md5 function (#43)
1 parent 623d073 commit 737c445

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Source/AwsCommonRuntimeKit/Utilities.swift

+16
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import struct Foundation.Date
55
import struct Foundation.Data
66
import class Foundation.FileHandle
77
import AwsCCommon
8+
import AwsCCal
89

910
@inlinable
1011
func zeroStruct<T>(_ ptr: UnsafeMutablePointer<T>) {
@@ -25,6 +26,21 @@ extension String {
2526
var awsByteCursor: aws_byte_cursor {
2627
return aws_byte_cursor_from_c_str(self.asCStr())
2728
}
29+
30+
public func base64EncodedMD5(allocator: Allocator = defaultAllocator, truncate: Int = 0) -> String? {
31+
let input: UnsafePointer<aws_byte_cursor> = fromPointer(ptr: self.awsByteCursor)
32+
let emptyBuffer: UInt8 = 0
33+
let bufferPtr: UnsafeMutablePointer<UInt8> = fromPointer(ptr: emptyBuffer)
34+
let buffer = aws_byte_buf(len: 0, buffer: bufferPtr, capacity: 16, allocator: allocator.rawValue)
35+
let output: UnsafeMutablePointer<aws_byte_buf> = fromPointer(ptr: buffer)
36+
37+
guard AWS_OP_SUCCESS == aws_md5_compute(allocator.rawValue, input, output, truncate) else {
38+
return nil
39+
}
40+
41+
let byteCursor = aws_byte_cursor_from_buf(output)
42+
return byteCursor.toData().base64EncodedString()
43+
}
2844
}
2945

3046
public extension Int32 {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0.
3+
import XCTest
4+
#if os(Linux)
5+
import Glibc
6+
#else
7+
import Darwin
8+
#endif
9+
@testable import AwsCommonRuntimeKit
10+
11+
class UtilityTests: XCTestCase {
12+
func testMd5() throws {
13+
let hello = "Hello"
14+
let md5 = hello.base64EncodedMD5()
15+
XCTAssertEqual(md5, "ixqZU8RhEpaoJ6v4xHgE1w==")
16+
}
17+
18+
func testMd5_payload() throws {
19+
let payload = "{\"foo\":\"base64 encoded md5 checksum\"}"
20+
21+
let md5 = payload.base64EncodedMD5()
22+
23+
XCTAssertEqual(md5, "iB0/3YSo7maijL0IGOgA9g==")
24+
}
25+
}
26+

0 commit comments

Comments
 (0)