3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

swiftでS3のマルチパートアップロード時のETagを計算する

Posted at

CommonCrypto.hインポート

ブリッジヘッダにCommonCrypto.hをインポートする。
このファイルはswiftプロジェクトでObjective-Cのファイルを作成すると作れる。作ったObjective-Cのファイルは削除してOK。

project-Bridging-Header.h
# import <CommonCrypto/CommonCrypto.h>

extension作成

別ファイルにするやり方がわからなかったのでメソッドを使うファイルに書いてます
別ファイルにするやり方誰か教えてください ;-(

extensions.swift
extension NSData {
    func s3etag(minimumPartSize: UInt64 = 5 * 1024 * 1024) -> String {
        func md5digest(data: NSData) -> NSData {
            let digestLength = Int(CC_MD5_DIGEST_LENGTH)
            let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
            
            CC_MD5(data.bytes, CC_LONG(data.length), md5Buffer)
            return NSMutableData(bytesNoCopy: md5Buffer, length: digestLength)
        }
        func md5hexdigext(data: NSData) -> String {
            let digestLength = Int(CC_MD5_DIGEST_LENGTH)
            let md5Buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLength)
            CC_MD5(data.bytes, CC_LONG(data.length), md5Buffer)
            var output = NSMutableString(capacity: Int(CC_MD5_DIGEST_LENGTH * 2))
            for i in 0..<digestLength {
                output.appendFormat("%02x", md5Buffer[i])
            }
            return String(format: output)
        }
        var size = UInt64(self.length)
        if size > minimumPartSize {
            var md5s = NSMutableData()
            var partCount = UInt64((size + (minimumPartSize / 2)) / minimumPartSize)
            for var i:UInt64=0; i<partCount; i++ {
                var dataStart  = Int(i * minimumPartSize);
                var dataLength = Int((i == (partCount - 1)) ? (size - (i * minimumPartSize)) : minimumPartSize)
                md5s.appendData(md5digest(self.subdataWithRange(NSMakeRange(dataStart, dataLength))))
            }
            return md5hexdigext(md5s) + "-" + String(partCount);
        } else {
            return md5hexdigext(self)
        }
    }
}

swift的にバイナリデータ扱うのはNSData使えばいいのか、全然違う方法があるのか、、、うーん。。。

こちら参考にさせてもらいました。
http://stackoverflow.com/questions/24123518/how-to-use-cc-md5-method-in-swift-language

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?