Thursday, 27 December 2018

iOS Swift 4:How to perform encryption/decryption with DES-ECB-PKCS5Padding?

I want to perform encryption/decryption with DES-ECB-PKCS5Padding in iOS Swift.

I have some code from Server Side (most probably in ActionScript) to help which is as follows:

private static const type:String='simple-des-ecb';

public static function encrypt(txt:String, salt:String): String
{
    var key:ByteArray = Hex.toArray(Hex.fromString(salt));
    var data:ByteArray = Hex.toArray(Hex.fromString(txt));
    var pad:IPad = new PKCS5;
    var mode:ICipher = Crypto.getCipher(type, key, pad);
    pad.setBlockSize(mode.getBlockSize());
    mode.encrypt(data);
    data.position = 0;
    return Base64.encodeByteArray(data);
}

public static function decrypt(txt:String, salt:String): String
{
    var key:ByteArray = Hex.toArray(Hex.fromString(salt));
    var data:ByteArray = Base64.decodeToByteArray(txt);
    var pad:IPad = new PKCS5;
    var mode:ICipher = Crypto.getCipher(type, key, pad);
    pad.setBlockSize(mode.getBlockSize());
    try
    {
        mode.decrypt(data);
    }
    catch (e:Error)
    {
        trace(e.message);
        trace(e.getStackTrace());
    }
    return Hex.toString(Hex.fromArray(data));
}

I have tried to reciprocate the above functions in Swift, but I'm unable to get desired results

My Swift code goes as follows:

func encrypt(text: String, salt: String) -> String {

    let strHexKey = hexFromString(string: salt)
    let key = strHexKey.hexaBytes

    let strHexData = hexFromString(string: text)
    let data = strHexData.hexaBytes

    let cryptor = Cryptor(operation: .encrypt, algorithm: .des, options: .PKCS7Padding, key: key, iv: Array<UInt8>())
    let cipherText = cryptor.update(byteArray: data)?.final()

    let strBase64 = cipherText!.data.base64EncodedString()

    return strBase64

}

func decrypt(text: String, salt: String) -> String {

    let strHexKey = hexFromString(string: salt)
    let key = arrayFrom(hexString: strHexKey)

    let data = text.fromBase64()?.data(using: .utf8)

    let cryptor = Cryptor(operation: .decrypt, algorithm: .des, options: .PKCS7Padding, key: key, iv: Array<UInt8>())
    let cipherText = cryptor.update(data: data!)!.final()

    return (cipherText?.hexa)!

}

I have been using https://github.com/iosdevzone/IDZSwiftCommonCrypto for Cryptor Library

Please help me where am I going wrong.

Thanks in Advance!!!



from iOS Swift 4:How to perform encryption/decryption with DES-ECB-PKCS5Padding?

No comments:

Post a Comment