iosswiftencryptiondes

DES Encryption and decryption algorithm in swift


I am trying to use DES algorithm for Encryption and decryption in swift

But with the code that I have written the encrypted message is changing for every build

Here is my code:

import UIKit
import CommonCrypto

public class IAppEncryptionUtitlity: NSObject {
    private override init(){}
    public static let sharedNetworkVar: IAppEncryptionUtitlity = IAppEncryptionUtitlity()
    let key = IAppConfig.key
     func myEncrypt(encryptData:String) -> NSData?{

        var myKeyData : NSData = ("DyfmgL9p" as NSString).data(using: String.Encoding.utf8.rawValue)! as NSData
        var myRawData : NSData = encryptData.data(using: String.Encoding.utf8)! as NSData
        var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205]  // I didn't use
        var buffer_size : size_t = myRawData.length + kCCBlockSize3DES
        var buffer = UnsafeMutablePointer<NSData>.allocate(capacity: buffer_size)
        var num_bytes_encrypted : size_t = 0

        let operation: CCOperation = UInt32(kCCEncrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
        let options:   CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
        let keyLength        = size_t(kCCKeySize3DES)

        var Crypto_status: CCCryptorStatus = CCCrypt(operation, algoritm, options, myKeyData.bytes, keyLength, nil, myRawData.bytes, myRawData.length, buffer, buffer_size, &num_bytes_encrypted)

        if UInt32(Crypto_status) == UInt32(kCCSuccess){

            var myResult: NSData = NSData(bytes: buffer, length: num_bytes_encrypted)

            free(buffer)
            print("my result \(myResult)") //This just prints the data

            let keyData: NSData = myResult

            let hexString = keyData.hexEncodedString()
            print("hex result \(keyData)") // I needed a hex string output


            //myDecrypt(decryptData: myResult) // sent straight to the decryption function to test the data output is the same
            return myResult
        }else{
            free(buffer)
            return nil
        }
    }
    func myDecrypt(decryptData : NSData) -> NSData?{

        var mydata_len : Int = decryptData.length
        var keyData : NSData = ("myEncryptionKey" as NSString).data(using: String.Encoding.utf8.rawValue)! as NSData

        var buffer_size : size_t = mydata_len+kCCBlockSizeAES128
        var buffer = UnsafeMutablePointer<NSData>.allocate(capacity: buffer_size)
        var num_bytes_encrypted : size_t = 0

        var iv : [UInt8] = [56, 101, 63, 23, 96, 182, 209, 205]  // I didn't use

        let operation: CCOperation = UInt32(kCCDecrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
        let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)
        let keyLength        = size_t(kCCKeySize3DES)

        var decrypt_status : CCCryptorStatus = CCCrypt(operation, algoritm, options, keyData.bytes, keyLength, nil, decryptData.bytes, mydata_len, buffer, buffer_size, &num_bytes_encrypted)

        if UInt32(decrypt_status) == UInt32(kCCSuccess){

            var myResult : NSData = NSData(bytes: buffer, length: num_bytes_encrypted)
            free(buffer)
            print("decrypt \(myResult)")

            var stringResult = NSString(data: myResult as Data, encoding:String.Encoding.utf8.rawValue)
            print("my decrypt string \(stringResult!)")
            return myResult
        }else{
            free(buffer)
            return nil

        }
    }
}
extension NSData {
    struct HexEncodingOptions: OptionSet {
        let rawValue: Int
        static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
    }

    func hexEncodedString(options: HexEncodingOptions = []) -> String {
        let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
        //var map = { String(format: format, $0) }.joined()

        return ""
    }
}

Output is changing for every build . Whats wrong in the code or

And is kCCOptionPKCS7Padding and kCCOptionPKCS5Padding is same?

Thanks In advance


Solution

  • Got Solution by changing the code

    import UIKit
    import CommonCrypto
    var message: String?
    
    public class IAppEncryptionUtitlity: NSObject {
    
       //Calling method to encrypt using extensions
        public func methodToCallEncryption( stringToEncrypt : String ) ->String {
            let iVValue:String = "nzug8FrX"
            let keyValue = IAppConfig.key //DyfmgL9p
            let encoded = stringToEncrypt.desEncrypt( key : keyValue , iv : iVValue )
            return encoded!
        }
    
        public func methodToCallDecryption( stringToDecrypt : String ) -> String{
            let iVValue:String = "nzug8FrX"
            let keyValue = IAppConfig.key //DyfmgL9p
            let decoded = stringToDecrypt.desEncrypt( key : keyValue , iv : iVValue )
            return decoded!
        }
    }
    extension String {
    
        func desEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
            if let keyData = key.data(using: String.Encoding.utf8),
                let data = self.data(using: String.Encoding.utf8),
                let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeDES) {
    
    
                let keyLength              = size_t(kCCKeySizeDES)
                let operation: CCOperation = UInt32(kCCEncrypt)
                let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmDES)
                let options:   CCOptions   = UInt32(options)
    
    
    
                var numBytesEncrypted :size_t = 0
    
                let cryptStatus = CCCrypt(operation,
                                          algoritm,
                                          options,
                                          (keyData as NSData).bytes, keyLength,
                                          iv,
                                          (data as NSData).bytes, data.count,
                                          cryptData.mutableBytes, cryptData.length,
                                          &numBytesEncrypted)
    
                if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                    cryptData.length = Int(numBytesEncrypted)
                    let base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
                    return base64cryptString
    
                }
                else {
                    return nil
                }
            }
            return nil
        }
    
        func desDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
            if let keyData = key.data(using: String.Encoding.utf8),
                let data = NSData(base64Encoded: self, options: .ignoreUnknownCharacters),
                let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeDES) {
    
                let keyLength              = size_t(kCCKeySizeDES)
                let operation: CCOperation = UInt32(kCCDecrypt)
                let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmDES)
                let options:   CCOptions   = UInt32(options)
    
                var numBytesEncrypted :size_t = 0
    
                let cryptStatus = CCCrypt(operation,
                                          algoritm,
                                          options,
                                          (keyData as NSData).bytes, keyLength,
                                          iv,
                                          data.bytes, data.length,
                                          cryptData.mutableBytes, cryptData.length,
                                          &numBytesEncrypted)
    
                if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                    cryptData.length = Int(numBytesEncrypted)
                    let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
                    return unencryptedMessage
                }
                else {
                    return nil
                }
            }
            return nil
        }
    }
    

    Thanks everyone for the help