puja
puja

Reputation: 239

Openssl-aes-256-cbc encryption in iOS

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

Upvotes: 1

Views: 1304

Answers (1)

wzso
wzso

Reputation: 3905

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.

Upvotes: 0

Related Questions