Post

Replies

Boosts

Views

Activity

Swift AES CBC 256 Encryption With Static 32bit Key and 32bit IV
We have the below Implementation in Android and the same has to be integrated into Swift. Key :- "d95acd54b4a821ff32c52825q931c194" IV :- "687b9509c25a34b8ad076346s8353d67" Here Both the Key and IV are 32 bits and below is the android code. public class AESEncryption { private static final String key = "d95acd54c6a821ff32c52825b931c194"; private static final String initVector = "687b9509c25a14b8ad076346d8353d67"; static byte[] bte = hexToBytes(initVector); public static String encrypt(String strToEncrypt) { try { CommonCode.showLog("log", bte.toString()); IvParameterSpec iv = new IvParameterSpec(bte); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); CommonCode.showLog("IV after logs", iv.toString()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(strToEncrypt.getBytes()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { return Base64.getEncoder().encodeToString(encrypted).trim(); } else { return android.util.Base64.encodeToString(encrypted, android.util.Base64.DEFAULT).trim(); } } catch (Exception e) { CommonCode.showLog("Error while encrypting: ", e.toString()); } return null; } public static String decrypt(String strToDecrypt) { try { IvParameterSpec iv = new IvParameterSpec(bte); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } else { return new String(cipher.doFinal(android.util.Base64.decode(strToDecrypt, android.util.Base64.DEFAULT))); } } catch (Exception e) { CommonCode.showLog("Error while decrypting: " , e.toString()); } return null; } } How can we mimic the above in Swift? Here in Android they are using static byte[] bte = hexToBytes(initVector); to convert the 32bit IV into 16 bit Bytes Array I Have Tried the same approach on Swift below are the code snippet [Contents.swift](https://developer.apple.com/forums/content/attachment/60fab4f2-1496-4003-9f37-c195de95e94a)
9
0
8.4k
Aug ’21