1

I am working on Encryption,Decryption in swift OpenSSl AES-256-CBC. I have checked with many third- party libraries or pods i.e. CryptoSwift and many others. But I am always getting HMAc is Not valid from Php back end team. Where as in android they have done this:

Following is my android method:

public EncryptedData encrypt(Object data) throws Exception {
    String text;
    if (data instanceof String) {
        text = String.valueOf(data);
    } else {
        text = (new Gson()).toJson(data);
    }

    if (!this.doAction) {
        return new EncryptedData(text, "");
    } else {
        this.ivspec = new IvParameterSpec(this.getIV1().getBytes());
        this.keyspec = new SecretKeySpec(this.getKey1().getBytes(), "AES");
        if (text != null && text.length() != 0) {
            byte[] encrypted;
            try {
                this.cipher.init(Cipher.ENCRYPT_MODE, this.keyspec, this.ivspec);
                encrypted = this.cipher.doFinal(this.padString(text).getBytes());
            } catch (Exception var5) {
                throw new Exception("[encrypt] " + var5.getMessage());
            }
            String encryptedData = new String(Base64.encode(encrypted, Base64.DEFAULT))
                    .replace("\n", "");

            SecretKeySpec macKey = new SecretKeySpec(getKey1().getBytes(), "HmacSHA256");
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(macKey);
            hmacSha256.update((Base64.encodeToString(getIV1().getBytes(), Base64.DEFAULT).trim() + encryptedData.trim()).getBytes());
            byte[] calcMac = hmacSha256.doFinal();

            return new EncryptedData(encryptedData, bytesToHex(calcMac));
        } else {
            throw new Exception("Empty string");
        }
    }
}

Any one know how this will works in iOS. Any help will be appreciated. Thanks

puja
  • 209
  • 1
  • 15
  • It is best to avoid using CryptoSwift, among other things it is 500 to 1000 times slower than Common Crypto based implementations. Apple's Common Crypto is FIPS certified and as such has been well vetted, using CryptoSwift is taking a chance on correctness, possible timing attacks and security such as timing and power attacks. – zaph Jul 27 '18 at 11:54
  • For HMAC Common Crypto example code see [this answer](https://stackoverflow.com/a/46282026/451475). – zaph Jul 27 '18 at 11:59

1 Answers1

0

Here is a simple HMAC implement in Swift 4:

0xa6a/HMAC

No third-party library is needed. Just create a bridging header and import <CommonCrypto/CommonCrypto.h> in it.

Have a try and happy coding.

wzso
  • 3,482
  • 5
  • 27
  • 48