-
Notifications
You must be signed in to change notification settings - Fork 0
iOS: consolidate SHA-256 hashing into a shared utility #47
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| #import <Foundation/Foundation.h> | ||
|
|
||
| NS_ASSUME_NONNULL_BEGIN | ||
|
|
||
| // SHA-256 hex digest of a file's contents. | ||
| // Returns nil and sets *error if the file can't be opened/read. | ||
| NSString * _Nullable CodePushSha256HexForFile(NSString *filePath, NSError **error); | ||
|
|
||
| // SHA-256 hex digest of an in-memory buffer. | ||
| NSString *CodePushSha256HexForData(NSData *data); | ||
|
|
||
| NS_ASSUME_NONNULL_END |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| #import "CodePushSha256.h" | ||
| #include <CommonCrypto/CommonDigest.h> | ||
|
|
||
| static NSString *const CodePushSha256ErrorDomain = @"CodePushSha256Error"; | ||
|
|
||
| static NSString *hexStringForDigest(unsigned char digest[CC_SHA256_DIGEST_LENGTH]) | ||
| { | ||
| NSMutableString *hex = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; | ||
| for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { | ||
| [hex appendFormat:@"%02x", digest[i]]; | ||
| } | ||
| return hex; | ||
| } | ||
|
|
||
| NSString *CodePushSha256HexForData(NSData *data) | ||
| { | ||
| unsigned char digest[CC_SHA256_DIGEST_LENGTH]; | ||
| CC_SHA256(data.bytes, (CC_LONG)data.length, digest); | ||
| return hexStringForDigest(digest); | ||
| } | ||
|
|
||
| NSString *CodePushSha256HexForFile(NSString *filePath, NSError **error) | ||
| { | ||
| NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath]; | ||
| if (!fileHandle) { | ||
| if (error) { | ||
| *error = [NSError errorWithDomain:CodePushSha256ErrorDomain | ||
| code:1 | ||
| userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Could not open file for reading: %@", filePath] }]; | ||
| } | ||
| return nil; | ||
| } | ||
|
|
||
| CC_SHA256_CTX context; | ||
| CC_SHA256_Init(&context); | ||
|
|
||
| static const NSUInteger kChunkSize = 1024 * 8; | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| NSError *readError; | ||
| while (YES) { | ||
| NSData *chunk = [fileHandle readDataUpToLength:kChunkSize error:&readError]; | ||
| if (readError) { | ||
| [fileHandle closeFile]; | ||
| if (error) { | ||
| *error = [NSError errorWithDomain:CodePushSha256ErrorDomain | ||
| code:2 | ||
| userInfo:@{ NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Could not read file: %@", filePath], | ||
| NSUnderlyingErrorKey: readError }]; | ||
| } | ||
| return nil; | ||
| } | ||
| if (chunk.length == 0) { | ||
| break; | ||
| } | ||
| CC_SHA256_Update(&context, chunk.bytes, (CC_LONG)chunk.length); | ||
| } | ||
| [fileHandle closeFile]; | ||
|
|
||
| unsigned char digest[CC_SHA256_DIGEST_LENGTH]; | ||
| CC_SHA256_Final(digest, &context); | ||
| return hexStringForDigest(digest); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,5 @@ | ||
| #import "CodePush.h" | ||
| #include <CommonCrypto/CommonDigest.h> | ||
| #import "CodePushSha256.h" | ||
|
Copilot marked this conversation as resolved.
|
||
| #import "JWT.h" | ||
|
|
||
| @implementation CodePushUpdateUtils | ||
|
|
@@ -57,23 +57,29 @@ + (BOOL)addContentsOfFolderToManifest:(NSString *)folderPath | |
| return NO; | ||
| } | ||
| } else { | ||
| NSData *fileContents = [NSData dataWithContentsOfFile:fullFilePath]; | ||
| NSString *fileContentsHash = [self computeHashForData:fileContents]; | ||
| NSString *fileContentsHash = CodePushSha256HexForFile(fullFilePath, error); | ||
| if (!fileContentsHash) { | ||
| return NO; | ||
| } | ||
| [manifest addObject:[[relativePath stringByAppendingString:@":"] stringByAppendingString:fileContentsHash]]; | ||
| } | ||
| } | ||
|
|
||
| return YES; | ||
| } | ||
|
|
||
| + (void)addFileToManifest:(NSURL *)fileURL | ||
| + (BOOL)addFileToManifest:(NSURL *)fileURL | ||
| manifest:(NSMutableArray *)manifest | ||
| error:(NSError **)error | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. File reading errors were previously unhandled, that's why the signature is changing (standard ObjC error handling pattern). |
||
| { | ||
| if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) { | ||
| NSData *fileContents = [NSData dataWithContentsOfURL:fileURL]; | ||
| NSString *fileContentsHash = [self computeHashForData:fileContents]; | ||
| NSString *fileContentsHash = CodePushSha256HexForFile([fileURL path], error); | ||
| if (!fileContentsHash) { | ||
| return NO; | ||
| } | ||
| [manifest addObject:[NSString stringWithFormat:@"%@/%@:%@", [self manifestFolderPrefix], [fileURL lastPathComponent], fileContentsHash]]; | ||
| } | ||
| return YES; | ||
| } | ||
|
|
||
| + (NSString *)computeFinalHashFromManifest:(NSMutableArray *)manifest | ||
|
|
@@ -93,19 +99,7 @@ + (NSString *)computeFinalHashFromManifest:(NSMutableArray *)manifest | |
| // The JSON serialization turns path separators into "\/", e.g. "CodePush\/assets\/image.png" | ||
| manifestString = [manifestString stringByReplacingOccurrencesOfString:@"\\/" | ||
| withString:@"/"]; | ||
| return [self computeHashForData:[NSData dataWithBytes:manifestString.UTF8String length:[manifestString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]]; | ||
| } | ||
|
|
||
| + (NSString *)computeHashForData:(NSData *)inputData | ||
| { | ||
| uint8_t digest[CC_SHA256_DIGEST_LENGTH]; | ||
| CC_SHA256(inputData.bytes, (CC_LONG)inputData.length, digest); | ||
| NSMutableString* inputHash = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; | ||
| for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { | ||
| [inputHash appendFormat:@"%02x", digest[i]]; | ||
| } | ||
|
|
||
| return inputHash; | ||
| return CodePushSha256HexForData([NSData dataWithBytes:manifestString.UTF8String length:[manifestString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]); | ||
| } | ||
|
|
||
| + (BOOL)copyEntriesInFolder:(NSString *)sourceFolder | ||
|
|
@@ -230,8 +224,12 @@ + (NSString *)getHashForBinaryContents:(NSURL *)binaryBundleUrl | |
| } | ||
| } | ||
|
|
||
| [self addFileToManifest:binaryBundleUrl manifest:manifest]; | ||
| [self addFileToManifest:[binaryBundleUrl URLByAppendingPathExtension:@"meta"] manifest:manifest]; | ||
| if (![self addFileToManifest:binaryBundleUrl manifest:manifest error:error]) { | ||
| return nil; | ||
| } | ||
| if (![self addFileToManifest:[binaryBundleUrl URLByAppendingPathExtension:@"meta"] manifest:manifest error:error]) { | ||
| return nil; | ||
| } | ||
|
|
||
| binaryHash = [self computeFinalHashFromManifest:manifest error:error]; | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import XCTest | ||
| import CryptoKit | ||
|
|
||
| final class CodePushSha256Tests: XCTestCase { | ||
|
|
||
| private var tempDir: URL! | ||
|
|
||
| override func setUpWithError() throws { | ||
| tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) | ||
| try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) | ||
| } | ||
|
|
||
| override func tearDownWithError() throws { | ||
| try? FileManager.default.removeItem(at: tempDir) | ||
| } | ||
|
|
||
| private func writeFile(named name: String, contents: Data) throws -> URL { | ||
| let url = tempDir.appendingPathComponent(name) | ||
| try contents.write(to: url) | ||
| return url | ||
| } | ||
|
|
||
| func testHexForFile_matchesExpectedDigest() throws { | ||
| let url = try writeFile(named: "abc.dat", contents: Data("abc".utf8)) | ||
|
|
||
| var error: NSError? | ||
| let hex = CodePushSha256HexForFile(url.path, &error) | ||
|
|
||
| XCTAssertNil(error) | ||
| XCTAssertEqual(hex, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") | ||
| } | ||
|
|
||
| func testHexForFile_emptyFile_matchesEmptyStringDigest() throws { | ||
| let url = try writeFile(named: "empty.dat", contents: Data()) | ||
|
|
||
| var error: NSError? | ||
| let hex = CodePushSha256HexForFile(url.path, &error) | ||
|
|
||
| XCTAssertNil(error) | ||
| XCTAssertEqual(hex, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") | ||
| } | ||
|
|
||
| func testHexForFile_largerThanChunkSize_matchesExpectedDigest() throws { | ||
| // Deterministic payload larger than the implementation's 8 KiB read-chunk | ||
| // boundary, so this exercises the multi-chunk CC_SHA256_Update loop rather | ||
| // than only its first iteration. | ||
| let payload = Data((0..<(8 * 1024 + 173)).map { UInt8($0 % 256) }) | ||
| let url = try writeFile(named: "large.dat", contents: payload) | ||
| let expectedHex = SHA256.hash(data: payload) | ||
| .map { String(format: "%02x", $0) } | ||
| .joined() | ||
|
|
||
| var error: NSError? | ||
| let hex = CodePushSha256HexForFile(url.path, &error) | ||
|
|
||
| XCTAssertNil(error) | ||
| XCTAssertEqual(hex, expectedHex) | ||
| } | ||
|
|
||
| func testHexForFile_missingFile_returnsNilAndSetsError() { | ||
| let missingURL = tempDir.appendingPathComponent("does_not_exist.dat") | ||
|
|
||
| var error: NSError? | ||
| let hex = CodePushSha256HexForFile(missingURL.path, &error) | ||
|
|
||
| XCTAssertNil(hex) | ||
| XCTAssertNotNil(error) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| #import "bspatch_bridge.h" | ||
| #import "CodePushSha256.h" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.