快速的DES加密和解密算法

时间:2019-02-25 09:13:03

标签: ios swift encryption des

我正在尝试使用DES算法快速进行加密和解密

但是随着我编写的代码的加密,消息对于每个构建都在变化

这是我的代码:

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 ""
    }
}

每个构建的输出都在变化。代码或

有什么问题

kCCOptionPKCS7Padding和kCCOptionPKCS5Padding是相同的吗?

预先感谢

2 个答案:

答案 0 :(得分:1)

通过更改代码获得解决方案

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
    }
}

感谢大家的帮助

答案 1 :(得分:0)

我们可以使用如下所示的字符串类别进行所有对称加密和解密,包括 DES、3DES 和 AES。

fromDataStream

完整来源: https://gist.github.com/tharindu/1cf0201492e41f1c287e51abb02902cd