11
9

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 3 で文字列を sha1、MD5 でハッシュ化する

Last updated at Posted at 2017-03-13

色々調べてみたけど、Swift3系でそのまま動かなかったので、メモとして残します。

準備

Objective-C のライブラリを使うので、Swift で使う場合は、Bridging-Header.h に下記の行を追加

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

sha1 の場合

let data = "文字列".data(using: .utf8)!
let length = Int(CC_SHA1_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: length)
_ = data.withUnsafeBytes { CC_SHA1($0, CC_LONG(data.count), &digest) }
let crypt = digest.map { String(format: "%02x", $0) }.joined(separator: "")

MD5 の場合

let data = "文字列".data(using: .utf8)!
let length = Int(CC_MD5_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: length)
_ = data.withUnsafeBytes { CC_MD5($0, CC_LONG(data.count), &digest) }
let crypt = digest.map { String(format: "%02x", $0) }.joined(separator: "")

解説

  • data.withUnsafeBytes は戻り値を _ = で捨てています。
    無いと Result of call to 'withUnsafeBytes' is unused とワーニング出ます。

  • String(format: "%02x", $0) の箇所を、String($0, raddix: 16) と書いてる記事もありますが、0 が消えるので、format 指定にしています。

11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?