Giter VIP home page Giter VIP logo

golden-key's Introduction

GoldenKey

GoldenKey

Swift wrapper around CommonCrypto and Security frameworks

Common Digest

Supported algorithms: MD2, MD4, MD5, SHA1, SHA224, SHA256, SHA384, SHA512.

Stream hasher.

let sha = SHA256()
sha.update(data: Data("12".utf8))
sha.update(data: [1, 2])

let degest = sha.finalize()

One shot.

let digest = SHA256.hash(data: Data("123".utf8))

All hash functions return type conform to Digest protocol . You can convert digest to common types like a Data and [UInt8].

let data = Data(digest)
let bytes: [UInt8] = Array(digest)

HMAC

hash-based message authentication code

Stream hasher.

let key = Data("secret_key".utf8)
let hmac = HMAC(algorithm: .md5, key: key)

hmac.update(data: Data("ab".utf8))
hmac.update(data: Data("cd".utf8))
let hash = hmac.finalize()

One shot.

let key = Data("secret_key".utf8)
let data = Data("abcd".utf8)

let hash = HMAC.hash(algorithm: .sha224, data: data, key: key)

Setup for development

$ mkdir gyb
$ cd gyb
$ wget https://github.com/apple/swift/raw/master/utils/gyb
$ wget https://github.com/apple/swift/raw/master/utils/gyb.py
$ chmod +x gyb

Efficient way to calculate hash of a large file

To calculate hash of a large file use DispatchIO.

In the example below DispatchIO reads a file by chunks and process every chunk by calling update method of SHA256 class.

The default chunk size is set to 128 MB to limit maximum memory usage.

Screenshot

import Foundation
import GoldenKey

final class FileHash {
    
    private let workQueue: DispatchQueue
    private let dispatchIO: DispatchIO
    
    /// Opens and prepares a file for reading.
    /// - Parameter fileURL: URL of the file.
    /// - Parameter workQueue: DispatchQueue on which to perform work (read and calculating hash).
    /// - Parameter queue: DispatchQueue of the completion handler.
    /// - Parameter completion: Calls when the file closed. Useful when you want to calculate hash of multiple files sequentially.
    init(
        fileURL: URL,
        workQueue: DispatchQueue = .init(label: "work", qos: .userInitiated),
        queue: DispatchQueue = .main,
        completion: (() -> Void)? = nil) throws {
        
        self.workQueue = workQueue
        
        let fileHandle = try FileHandle(forReadingFrom: fileURL)
        
        dispatchIO = DispatchIO(
            type: .stream,
            fileDescriptor: fileHandle.fileDescriptor,
            queue: queue,
            cleanupHandler: { _ in
                fileHandle.closeFile()
                queue.async { completion?() }
            }
        )
        dispatchIO.setLimit(lowWater: Int.max)
    }
    
    /// Calculates hash of the file
    /// - Parameter hashFunctionType: Hash function type. SHA256.self for example.
    /// - Parameter chunkSize: Max memory usage. 128 MB by default.
    /// - Parameter queue: DispatchQueue of the completion handler.
    /// - Parameter completion: Completion handler.
    func calculateHash(
        hashFunctionType: Digest.Type,
        chunkSize: Int = 128 * 1024 * 1024,
        queue: DispatchQueue = .main,
        completion: @escaping (Result<Data, POSIXError>) -> Void) {
        
        let hashFunction = hashFunctionType.init()
        
        func readNextChunk() {
            dispatchIO.read(offset: 0, length: chunkSize, queue: workQueue) { [weak self] (done, data, error) in
                guard let self = self else { return }
                
                guard error == 0 else {
                    let error = POSIXError(POSIXErrorCode(rawValue: error)!)
                    self.dispatchIO.close(flags: .stop)
                    queue.async {
                        completion(.failure(error))
                    }
                    return
                }
                
                guard let data = data else { return }
                
                if data.isEmpty == false {
                    data.regions.forEach { hashFunction.update(data: $0) }
                }
                
                if done, data.isEmpty {
                    self.dispatchIO.close()
                    
                    let digest = hashFunction.finalize()
                    queue.async {
                        completion(.success(digest))
                    }
                }
                
                if done, data.isEmpty == false {
                    readNextChunk()
                }
            }
        }
        
        readNextChunk()
    }
    
}

Usage example

extension Data {
    /// Presents Data in hex format
    var hexDescription: String {
        return reduce("") {$0 + String(format: "%02x", $1)}
    }
}

do {
    let fileURL = URL(string: "absolute_path_to_file")!
    let fileHash = try FileHash(fileURL: fileURL)
    fileHash.calculateHash(hashFunctionType: SHA256.self) { result in
        switch result {
        case .success(let hash):
            print(hash.hexDescription)
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
} catch (let error) {
    print(error.localizedDescription)
}

golden-key's People

Contributors

alexander-ignition avatar modestman avatar vani2 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

modestman subdan

golden-key's Issues

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.