-2

Java provides MAC(Message Authentication Code) algorithm API with which I can encrypt data by:

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

I am new in Swift, how can I implement the same thing as above with Swift 2 ?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • 1
    http://stackoverflow.com/questions/24099520/commonhmac-in-swift, http://stackoverflow.com/questions/26970807/implementing-hmac-and-sha1-encryption-in-swift, http://stackoverflow.com/questions/35620960/generating-hmac-sha256-from-byte-array-in-swift. – Martin R Sep 01 '16 at 17:13

1 Answers1

0
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)")

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]

Notes:

Add Security.framework to the project

For iOS:
Common Crypto must be imported, add
#import <CommonCrypto/CommonCrypto.h>
to the bridging header.

For OSX just import
#import <CommonCrypto/CommonCrypto.h>

zaph
  • 111,848
  • 21
  • 189
  • 228
  • Thanks, in Java code I provided, the function return type is array of `byte`, why in swift in your solution, the return type is array of `UInt8`? I need the exact same function like the Java code. – Leem.fin Sep 01 '16 at 18:46
  • `UInt8` is a byte. The `U` stands for "unsigned", `int` for "Integer" and `8` for "8-bits". This is a standard Swift type for a byte. The function returns an array of bytes. – zaph Sep 01 '16 at 19:03
  • Looks like this answer doesn't work for me, since I am neither developing iOS nor OSX project, I am writing a pure Swift project, I can't import CommonCrypto – Leem.fin Sep 01 '16 at 20:11
  • You should be able to the the [CroptoSwift](https://github.com/krzyzanowskim/CryptoSwift) project or at least the code from it. It is a terrible solution on a Mac or iOS device because it does not have hardware support and is hundreds to 1000 times slower than Apple's Common Crypto. – zaph Sep 01 '16 at 21:13