将objective-c代码转换为swift

时间:2015-09-21 13:29:29

标签: objective-c swift encryption commoncrypto cryptoswift

我真的需要一些帮助来使用CryptoSwift将objective-c代码转换为swift。我不确定如何在Swift中使用像bzerogetCStringmalloc这样的函数。

+(NSData*)encryptData:(NSData*)data
{
    static NSString *key = @"BitCave012345678";
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));

    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
                                          keyPtr,kCCKeySizeAES128,NULL,[data bytes],dataLength,
                                          buffer, bufferSize, &numBytesEncrypted);

    if(cryptStatus == kCCSuccess)
    {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }

    free(buffer);

    return nil;
}

有没有人知道如何满足需要指针的参数? 我正在尝试使用UnsafeMutablePointers,我也尝试了下面的代码,但我知道这是完全错误的:

var key: NSString = "BitCave012345678"
        var keyPtr: Array<Character> = Array<Character>(count: 17, repeatedValue: "0")
        bzero(&keyPtr, 17*sizeof(Character))
        key.getCString(&keyPtr, maxLength: 17*sizeof(Character), encoding: NSUTF8StringEncoding)

2 个答案:

答案 0 :(得分:2)

Swift 2.0

没有必要使用bzero,getCString,malloc,这是一个没有的例子:

将Security.framework添加到项目中 将#import添加到桥接头。

// operation is either 'kCCEncrypt' or 'kCCDecrypt'
func testCrypt(data data:NSData, keyData:NSData, operation:Int) -> NSData? {
    let keyBytes = UnsafePointer<UInt8>(keyData.bytes)

    let dataLength = Int(data.length)
    let dataBytes  = UnsafePointer<UInt8>(data.bytes)

    let cryptData: NSMutableData! = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)
    let cryptPointer = UnsafeMutablePointer<UInt8>(cryptData.mutableBytes)
    let cryptLength  = size_t(cryptData.length)

    let keyLength              = size_t(kCCKeySizeAES128)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
    let options:   CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)

    var numBytesEncrypted :size_t = 0

    let cryptStatus = CCCrypt(CCOperation(operation),
        algoritm,
        options,
        keyBytes, keyLength,
        nil,
        dataBytes, dataLength,
        cryptPointer, cryptLength,
        &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)

    } else {
        print("Error: \(cryptStatus)")
    }

    return cryptData;
}

使用示例:

let keyData     = "12345678901234567890123456789012".dataUsingEncoding(NSUTF8StringEncoding)
let messageData = "Don´t try to read this text. Top Secret Stuff".dataUsingEncoding(NSUTF8StringEncoding)
let encrypted = testCrypt(data:messageData!, keyData:keyData!, operation:kCCEncrypt)

以下是UInt8的Swift Arrays中没有NSData个对象的版本:

func testCrypt(data data:[UInt8], keyData:[UInt8], operation:Int) -> [UInt8]? {
    let keyBytes = UnsafeMutablePointer<UInt8>(keyData)

    let dataLength = data.count
    let dataBytes  = UnsafeMutablePointer<UInt8>(data)

    var cryptData = [UInt8](count:data.count+kCCBlockSizeAES128, repeatedValue:0)
    let cryptPointer = UnsafeMutablePointer<UInt8>(cryptData)
    let cryptLength  = size_t(cryptData.count)

    let keyLength              = size_t(kCCKeySizeAES128)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
    let options:   CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)

    var numBytesEncrypted :size_t = 0

    let cryptStatus = CCCrypt(CCOperation(operation),
        algoritm,
        options,
        keyBytes, keyLength,
        nil,
        dataBytes, dataLength,
        cryptPointer, cryptLength,
        &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.removeRange(numBytesEncrypted..<cryptData.count)

    } else {
        print("Error: \(cryptStatus)")
    }

    return cryptData;
}

使用示例:

let keyData     = Array("12345678901234567890123456789012".utf8)
let messageData = Array("Don´t try to read this text. Top Secret Stuff".utf8)
let encrypted   = testCrypt(data:messageData, keyData:keyData, operation:kCCEncrypt)

答案 1 :(得分:0)

我知道那里有更好的解决方案。但是我需要传统支持(旧数据库,已经加密),因此我将Barts Obj-C代码转换为 Swift 5 代码。也许有人也需要它。

extension Data {

    func aesDecrypt() -> Data? {

        let myKey:String = "BitCave012345678"

        var keyPtr = [Int8](repeating: 0, count: kCCKeySizeAES128+1)
        myKey.getCString(&keyPtr, maxLength: keyPtr.count, encoding: String.Encoding.utf8)

        var numBytesDecrypted :size_t = 0
        let dataLength:Int = self.count
        let bufferSize: size_t = dataLength + kCCBlockSizeAES128
        let bufferDecrypt = malloc(bufferSize)
        let iv = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]

        let result:CCCryptorStatus = CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), keyPtr, kCCKeySizeAES128, iv, self.bytes, self.count, bufferDecrypt, bufferSize, &numBytesDecrypted)

        if (result == kCCSuccess) {
            return Data(bytes: bufferDecrypt!, count: numBytesDecrypted)
        }

        free(bufferDecrypt)

        return nil
    }
}