Skip to content

Commit

Permalink
feat: expose md5 function (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
kneekey23 authored Aug 31, 2021
1 parent 623d073 commit 737c445
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Source/AwsCommonRuntimeKit/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import struct Foundation.Date
import struct Foundation.Data
import class Foundation.FileHandle
import AwsCCommon
import AwsCCal

@inlinable
func zeroStruct<T>(_ ptr: UnsafeMutablePointer<T>) {
Expand All @@ -25,6 +26,21 @@ extension String {
var awsByteCursor: aws_byte_cursor {
return aws_byte_cursor_from_c_str(self.asCStr())
}

public func base64EncodedMD5(allocator: Allocator = defaultAllocator, truncate: Int = 0) -> String? {
let input: UnsafePointer<aws_byte_cursor> = fromPointer(ptr: self.awsByteCursor)
let emptyBuffer: UInt8 = 0
let bufferPtr: UnsafeMutablePointer<UInt8> = fromPointer(ptr: emptyBuffer)
let buffer = aws_byte_buf(len: 0, buffer: bufferPtr, capacity: 16, allocator: allocator.rawValue)
let output: UnsafeMutablePointer<aws_byte_buf> = fromPointer(ptr: buffer)

guard AWS_OP_SUCCESS == aws_md5_compute(allocator.rawValue, input, output, truncate) else {
return nil
}

let byteCursor = aws_byte_cursor_from_buf(output)
return byteCursor.toData().base64EncodedString()
}
}

public extension Int32 {
Expand Down
26 changes: 26 additions & 0 deletions Test/AwsCommonRuntimeKitTests/crt/UtilityTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0.
import XCTest
#if os(Linux)
import Glibc
#else
import Darwin
#endif
@testable import AwsCommonRuntimeKit

class UtilityTests: XCTestCase {
func testMd5() throws {
let hello = "Hello"
let md5 = hello.base64EncodedMD5()
XCTAssertEqual(md5, "ixqZU8RhEpaoJ6v4xHgE1w==")
}

func testMd5_payload() throws {
let payload = "{\"foo\":\"base64 encoded md5 checksum\"}"

let md5 = payload.base64EncodedMD5()

XCTAssertEqual(md5, "iB0/3YSo7maijL0IGOgA9g==")
}
}

0 comments on commit 737c445

Please sign in to comment.