Java版:
public static byte[] computeSignature(String algorithm, byte[] data, byte[] sharedSecret) {
try {
SecretKey secretKey = new SecretKeySpec(sharedSecret, algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(secretKey);
return Base64.encode(mac.doFinal(data));
} catch (NoSuchAlgorithmException e) {
//
} catch (InvalidKeyException e) {
//
}
}
Swift版本:
func hmac(key: String) -> String {
let inputData: NSData = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let keyData: NSData = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
let algorithm = HMACAlgorithm.SHA1
let digestLen = CC_SHA1_DIGEST_LENGTH
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), keyData.bytes, keyData.length, inputData.bytes, inputData.length, result)
let data = NSData(bytes: result, length: digestLen)
result.destroy()
return data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
}
这是使用CryptoJs的javascript版本,它生成与java代码相同的hmacsha1哈希:https://jsfiddle.net/333VW/