1

I am new in Swift based Vapor backend framework, I just setup the HelloWorld project.

I need to use HMAC SHA256 algorithm to encrypt data. I searched on internet, and found something like this, but they are all based on iOS or OSX framework, which uses C library and can be added by import <CommonCrypto/CommonHMAC.h>.

How can I add CommonCrypto or HMAC to my Vapor project? If it is impossible, how can I have a pure swift HMAC Sha256 algorithm? Is there such dependency I can add to Package.swift ?

Community
  • 1
  • 1
Leem.fin
  • 40,781
  • 83
  • 202
  • 354

3 Answers3

4

If you're using Vapor 0.17 or later, you should be able to do import HMAC and import SHA2

From there you can easily create SHA1 hashes using HMAC.

Check out the Crypto package that Vapor uses: https://github.com/vapor/crypto

Additionally, Vapor's default hasher is SHA256 with HMAC. So you can do drop.hash.make("foo") and that will work.

tanner0101
  • 4,005
  • 19
  • 33
1

You should be able to the the 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. But is about as fast as possible in code only.

ıɾuǝʞ
  • 2,829
  • 26
  • 38
zaph
  • 111,848
  • 21
  • 189
  • 228
0

Agreed with @zaph answer, and if you want to use more optimized and fast solution, then import OpenSSL in swift using SPM (https://github.com/Zewo/OpenSSL) and then use OpenSSL based HMAC apis.

Reference: https://github.com/yoshiki/HMACHash/blob/master/Sources/HMACHash.swift

Ankit Thakur
  • 4,739
  • 1
  • 19
  • 35