Swift 4 中的 HMAC SHA256
HMAC SHA256 in Swift 4
我有一个字符串和一个密钥,我想从中生成一个 HMAC SHA256。虽然我使用了 2 个库
IDZSwiftCommonCrypto and CryptoSwift
没有什么对我有用。我的真实来源是那两个网站
和
https://www.freeformatter.com/hmac-generator.html#ad-output
他们总是为我的案例生成正确的散列键。
知道什么可以在这里工作吗?一些代码示例
对于 IDZSwiftCommonCrypto
func getHMacSHA256(forMessage message: String, key: String) -> String? {
let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()
if let encryptedData = hMacVal {
let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)
print("base64String: \(base64String)")
return base64String
} else {
return nil
}
}
对于 CryptoSwift
let password: Array<UInt8> = Array(payload.utf8)
let salt: Array<UInt8> = Array("somekey".utf8)
let signedBody = try? HKDF(password: password, salt: salt, variant: .sha256).calculate()
但是没有什么比 truth.Any idea 的来源更有效了?
我一直在用这个:
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.cString(using: String.Encoding.utf8)
let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let keyStr = key.cString(using: String.Encoding.utf8)
let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate(capacity: 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).lowercased()
}
}
您需要将 #import <CommonCrypto/CommonHMAC.h>
添加到 Objective-C 桥接头。
Swift 4.2 HMAC加密
的解决方案
不久前我遇到了同样的问题,所以我编写了用于所有平台上 Swift 的简单框架 - iOS macOS 和 tvOS
它叫做 EasyCrypt 你可以在这里找到它:
https://github.com/lukszar/EasyCrypt
此框架允许您使用 HMAC 算法使用您的密钥加密消息。
用法很简单,如下:
let crypto = EasyCrypt(secret: "mySecretKey", algorithm: .sha256)
let result = crypto.hash("This is very secret text to encrypt")
let otherResult = crypto.hash("This is another secret text to encrypt")
print("result: ", result)
print("otherResult: ", otherResult)
您可以使用 Carthage 快速安装。在项目中,您可以找到带有说明的演示用法的 Playground。
你用 CryptoSwift 做错了。
对于未来的读者,以下是操作方法:
let result = try! HMAC(key: key, variant: .sha256).authenticate(message.bytes)
如果您的目标是 iOS 13.0+ 或 macOS 10.15+,请使用 Apple 的 CryptoKit
import CryptoKit
let secretString = "my-secret"
let key = SymmetricKey(data: Data(secretString.utf8))
let string = "An apple a day keeps anyone away, if you throw it hard enough"
let signature = HMAC<SHA256>.authenticationCode(for: Data(string.utf8), using: key)
print(Data(signature).map { String(format: "%02hhx", [=10=]) }.joined()) // 1c161b971ab68e7acdb0b45cca7ae92d574613b77fca4bc7d5c4effab89dab67
我有一个字符串和一个密钥,我想从中生成一个 HMAC SHA256。虽然我使用了 2 个库
IDZSwiftCommonCrypto and CryptoSwift
没有什么对我有用。我的真实来源是那两个网站
和
https://www.freeformatter.com/hmac-generator.html#ad-output
他们总是为我的案例生成正确的散列键。 知道什么可以在这里工作吗?一些代码示例
对于 IDZSwiftCommonCrypto
func getHMacSHA256(forMessage message: String, key: String) -> String? {
let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()
if let encryptedData = hMacVal {
let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
let base64String = decData.base64EncodedString(options: .lineLength64Characters)
print("base64String: \(base64String)")
return base64String
} else {
return nil
}
}
对于 CryptoSwift
let password: Array<UInt8> = Array(payload.utf8)
let salt: Array<UInt8> = Array("somekey".utf8)
let signedBody = try? HKDF(password: password, salt: salt, variant: .sha256).calculate()
但是没有什么比 truth.Any idea 的来源更有效了?
我一直在用这个:
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.cString(using: String.Encoding.utf8)
let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let keyStr = key.cString(using: String.Encoding.utf8)
let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
let digest = stringFromResult(result: result, length: digestLen)
result.deallocate(capacity: 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).lowercased()
}
}
您需要将 #import <CommonCrypto/CommonHMAC.h>
添加到 Objective-C 桥接头。
Swift 4.2 HMAC加密
的解决方案不久前我遇到了同样的问题,所以我编写了用于所有平台上 Swift 的简单框架 - iOS macOS 和 tvOS
它叫做 EasyCrypt 你可以在这里找到它: https://github.com/lukszar/EasyCrypt
此框架允许您使用 HMAC 算法使用您的密钥加密消息。 用法很简单,如下:
let crypto = EasyCrypt(secret: "mySecretKey", algorithm: .sha256)
let result = crypto.hash("This is very secret text to encrypt")
let otherResult = crypto.hash("This is another secret text to encrypt")
print("result: ", result)
print("otherResult: ", otherResult)
您可以使用 Carthage 快速安装。在项目中,您可以找到带有说明的演示用法的 Playground。
你用 CryptoSwift 做错了。
对于未来的读者,以下是操作方法:
let result = try! HMAC(key: key, variant: .sha256).authenticate(message.bytes)
如果您的目标是 iOS 13.0+ 或 macOS 10.15+,请使用 Apple 的 CryptoKit
import CryptoKit
let secretString = "my-secret"
let key = SymmetricKey(data: Data(secretString.utf8))
let string = "An apple a day keeps anyone away, if you throw it hard enough"
let signature = HMAC<SHA256>.authenticationCode(for: Data(string.utf8), using: key)
print(Data(signature).map { String(format: "%02hhx", [=10=]) }.joined()) // 1c161b971ab68e7acdb0b45cca7ae92d574613b77fca4bc7d5c4effab89dab67