I need same crypto encrypt and decrypt function for IOS Swift 5

Viewed 16

I have implemented below class for encryption and decryption of string using a secret key (which is user password in my case)

I need to implement same in ios swift 5 , please guide

public class AES256 {

private  final String SECRET_KEY ;
private static final String SALT = "ssshhhhhhhhhhh!!!!";

public AES256(String secret_key) {
    SECRET_KEY = secret_key;
}

@RequiresApi(api = Build.VERSION_CODES.O)
public  String encrypt(String strToEncrypt) {
    try {
        byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
        return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8)));
    } catch (Exception e) {
        System.out.println("Error while encrypting: " + e.toString());
    }
    return null;
}

@RequiresApi(api = Build.VERSION_CODES.O)
public  String decrypt(String strToDecrypt) {
    try {
        byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALT.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    } catch (Exception e) {
        System.out.println("Error while decrypting: " + e.toString());
    }
    return null;
}

}

1 Answers

First of all use this 3rd party dependency: https://github.com/krzyzanowskim/CryptoSwift

And the code would look something like this, i haven't tested it, you might have to do some small adjustments, but i think it's a good starting point.

    let salt: [UInt8] = Array("ssshhhhhhhhhhh!!!!".utf8)
    let password: [UInt8] = Array("passwordpassword".utf8)
    
    func encrypt(msg: String) -> String {
        let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
        do {
            let key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096,keyLength: 32, variant: .sha2(.sha256)).calculate()
            let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs5)
            let encryptedData = try aes.encrypt(msg.bytes)
            
            let encryptedMessage = encryptedData.toHexString()
            
            return encryptedMessage
        } catch let err {
            print(err.localizedDescription)
        }
        return ""
    }
    
    func decrypt(encrMsg: String) -> String {
        let iv: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
        do {
            let key = try PKCS5.PBKDF2(password: password, salt: salt, iterations: 4096,keyLength: 32, variant: .sha2(.sha256)).calculate()
            let aes = try AES(key: key, blockMode: CBC(iv: iv), padding: .pkcs5)
            let decryptedData = try aes.decrypt(encrMsg.bytes)
            let decryptedMessage = decryptedData.toHexString()
            return decryptedMessage
        } catch let err {
            print(err.localizedDescription)
        }
        return ""
    }
Related