Skip to content

Commit

Permalink
feat: add sha256 checksum extension (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
kneekey23 authored Sep 29, 2021
1 parent 737c445 commit fcedf0c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
13 changes: 13 additions & 0 deletions Source/AwsCommonRuntimeKit/Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,19 @@ extension String {
let byteCursor = aws_byte_cursor_from_buf(output)
return byteCursor.toData().base64EncodedString()
}

public func base64EncodedSha256(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: Int(AWS_SHA256_LEN), allocator: allocator.rawValue)
let output: UnsafeMutablePointer<aws_byte_buf> = fromPointer(ptr: buffer)

aws_sha256_compute(allocator.rawValue, input, output, truncate)

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

public extension Int32 {
Expand Down
20 changes: 20 additions & 0 deletions Test/AwsCommonRuntimeKitTests/crt/UtilityTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,25 @@ class UtilityTests: XCTestCase {

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

func testSha256() throws {
let hello = "Hello"
let sha256 = hello.base64EncodedSha256()
XCTAssertEqual(sha256, "GF+NsyJx/iX1Yab8k4suJkMG7DBO2lGAB9F2SCY4GWk=")
}

func testSha256_EmptyString() throws {
let empty = ""
let sha256 = empty.base64EncodedSha256()
XCTAssertEqual(sha256, "47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=")
}

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

let sha256 = payload.base64EncodedSha256()

XCTAssertEqual(sha256, "lBSnDP4sj/yN8eIVOJlv+vC56hw+7JtN0132GiMQXRg=")
}
}

0 comments on commit fcedf0c

Please sign in to comment.