【问题标题】:HMAC encryption in Swift 2 [duplicate]Swift 2 中的 HMAC 加密
【发布时间】:2016-09-01 17:10:07
【问题描述】:

Java 提供了MAC(Message Authentication Code) algorithm API,我可以用它加密data

byte[] data = getDataBytes();
Mac mac = Mac.getInstance("HMAC-SHA256");
mac.init(new SecretKeySpec(key, "HMAC-SHA256"));
byte[] encryptedBytes = mac.doFinal(data);

我是 Swift 新手,如何使用 Swift 2 实现与上述相同的功能?

【问题讨论】:

标签: swift swift2 hmac


【解决方案1】:
func hmacSha256(string:String, key:String) -> [UInt8] {
    var mac = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
    if let dataBytes = string.dataUsingEncoding(NSUTF8StringEncoding) {
        if let keyBytes = key.dataUsingEncoding(NSUTF8StringEncoding) {
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256),
                   keyBytes.bytes,  keyBytes.length,
                   dataBytes.bytes, dataBytes.length,
                   &mac);
        }
    }

    return mac;
}
let hash = hmacSha256("InputString", key:"keyString")
print("hash: \(hash)")

哈希:[41, 226, 70, 65, 222, 197, 202, 78, 138, 62, 40, 93, 225, 228, 181, 178, 108, 158, 238, 25, 74, 199, 116、106、96、142、216、239、41、18、245、156]

注意事项:

Security.framework 添加到项目中

对于 iOS:
Common Crypto必须导入,添加
#import <CommonCrypto/CommonCrypto.h>
到桥接头。

对于 OSX 只需导入
#import <CommonCrypto/CommonCrypto.h>

【讨论】:

  • 谢谢,在我提供的Java代码中,函数返回类型是byte的数组,为什么在你的解决方案中,返回类型是UInt8的数组?我需要与 Java 代码完全相同的功能。
  • UInt8 是一个字节。 U 代表“无符号”,int 代表“整数”,8 代表“8 位”。这是一个字节的标准 Swift 类型。该函数返回一个字节数组。
  • 看起来这个答案对我不起作用,因为我既不开发 iOS 也不开发 OSX 项目,我正在编写一个纯 Swift 项目,我无法导入 CommonCrypto
  • 您应该可以使用CroptoSwift 项目或至少可以使用其中的代码。这在 Mac 或 iOS 设备上是一个糟糕的解决方案,因为它没有硬件支持,并且比 Apple 的 Common Crypto 慢数百到 1000 倍。
猜你喜欢
  • 2016-11-23
  • 2014-07-02
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2020-10-18
  • 1970-01-01
  • 2017-07-16
相关资源
最近更新 更多