1
|
#
import
<
CommonCrypto
/
CommonHMAC
.h>
|
(2)下面是一個封裝類,同時對String進行HMAC擴展。(除了SHA1,還可使用其它算法好比MD5,SHA224等)php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
//HMAC.swift
import
Foundation
enum
CryptoAlgorithm
{
case
MD5
,
SHA1
,
SHA224
,
SHA256
,
SHA384
,
SHA512
var
HMACAlgorithm
:
CCHmacAlgorithm
{
var
result:
Int
= 0
switch
self
{
case
.
MD5
: result = kCCHmacAlgMD5
case
.
SHA1
: result = kCCHmacAlgSHA1
case
.
SHA224
: result = kCCHmacAlgSHA224
case
.
SHA256
: result = kCCHmacAlgSHA256
case
.
SHA384
: result = kCCHmacAlgSHA384
case
.
SHA512
: result = kCCHmacAlgSHA512
}
return
CCHmacAlgorithm
(result)
}
var
digestLength:
Int
{
var
result:
Int32
= 0
switch
self
{
case
.
MD5
: result =
CC_MD5_DIGEST_LENGTH
case
.
SHA1
: result =
CC_SHA1_DIGEST_LENGTH
case
.
SHA224
: result =
CC_SHA224_DIGEST_LENGTH
case
.
SHA256
: result =
CC_SHA256_DIGEST_LENGTH
case
.
SHA384
: result =
CC_SHA384_DIGEST_LENGTH
case
.
SHA512
: result =
CC_SHA512_DIGEST_LENGTH
}
return
Int
(result)
}
}
extension
String
{
func
hmac(algorithm:
CryptoAlgorithm
, key:
String
) ->
String
{
let
str =
self
.cStringUsingEncoding(
NSUTF8StringEncoding
)
let
strLen =
Int
(
self
.lengthOfBytesUsingEncoding(
NSUTF8StringEncoding
))
let
digestLen = algorithm.digestLength
let
result =
UnsafeMutablePointer
<
CUnsignedChar
>.alloc(digestLen)
let
keyStr = key.cStringUsingEncoding(
NSUTF8StringEncoding
)
let
keyLen =
Int
(key.lengthOfBytesUsingEncoding(
NSUTF8StringEncoding
))
CCHmac
(algorithm.
HMACAlgorithm
, keyStr!, keyLen, str!, strLen, result)
let
digest = stringFromResult(result, length: digestLen)
result.dealloc(digestLen)
return
digest
}
private
func
stringFromResult(result:
UnsafeMutablePointer
<
CUnsignedChar
>, length:
Int
) ->
String
{
let
hash =
NSMutableString
()
for
i
in
0..<length {
hash.appendFormat(
"%02x"
, result[i])
}
return
String
(hash)
}
}
|
(3)測試樣例html
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let
str =
"welcome to hangge.com"
let
key =
"67FG"
let
hmacStr = str.hmac(.
SHA1
, key: key)
print
(
"原始字符串:\(str)"
)
print
(
"key:\(key)"
)
print
(
"HMAC運算結果:\(hmacStr)"
)
/**** 輸出 ******
原始字符串:welcome to hangge.com
key:67FG
HMAC運算結果:79a5f5b138b5646289a9648de035c80e9c5c14c7
*****/
|
原文出自:www.hangge.com 轉載請保留原文連接:http://www.hangge.com/blog/cache/detail_851.htmljava