使用 CommonCrypto 的 Swift AES 加密 [英] Swift AES encryption using CommonCrypto

查看:44
本文介绍了使用 CommonCrypto 的 Swift AES 加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Swift 2.1XCode 7.1 上开发 iOS 应用程序,我正在尝试使用 AES 128 位 进行简单加密,并且PKCS7 使用 CommonCrypto 库 进行填充.

I am working on an iOS app on XCode 7.1 with Swift 2.1 and I am trying to do simple encryption with AES 128 bit and PKCS7 padding using CommonCrypto library.

代码有效,但每次我尝试将 NSData 对象转换为 NSString 然后转换为 String 我得到一个 nil 并且应用程序崩溃.

The code works but every time I try to cast the NSData object to NSString then to String I get a nil and the app crashes.

我调试了应用程序并且 NSData 对象不是 nil.

I debugged the app and the NSData object is not nil.

当我尝试解开可选的字符串时发生错误.

The error occurs when I try to unwrap the String optional.

如何解决这个问题?并将 NSData 对象正确转换为字符串?这是我的代码

How to resolve this issue? and convert the NSData object to a String correctly? Here is my code

static func AESEncryption(phrase: String,key: String,ivKey: String,encryptOrDecrypt: Bool) -> String {

let phraseData = phrase.dataUsingEncoding(NSUTF8StringEncoding)
let ivData = ivKey.dataUsingEncoding(NSUTF8StringEncoding)
    let keyData: NSData! = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    let keyBytes         = UnsafePointer<Void>(keyData.bytes)
    let keyLength        = size_t(kCCKeySizeAES128)
    let dataLength       = Int(phraseData!.length)
    let dataBytes        = UnsafePointer<Void>(phraseData!.bytes)
    let bufferData       = NSMutableData(length: Int(dataLength) + kCCBlockSizeAES128)!
    let bufferPointer    = UnsafeMutablePointer<Void>(bufferData.mutableBytes)
    let bufferLength     = size_t(bufferData.length)
    let ivBuffer         = UnsafePointer<Void>(ivData!.bytes)
    var bytesDecrypted   = Int(0)

    let operation = encryptOrDecrypt ? UInt32(kCCEncrypt) : UInt32(kCCDecrypt)

    let algorithm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
    let options:   CCOptions   = UInt32(kCCOptionPKCS7Padding)

    let cryptStatus = CCCrypt(
        operation,
        algorithm,
        options,
        keyBytes,
        keyLength,
        ivBuffer,
        dataBytes,
        dataLength,
        bufferPointer,
        bufferLength,
        &bytesDecrypted)
    if Int32(cryptStatus) == Int32(kCCSuccess) {
        bufferData.length = bytesDecrypted

        let data = bufferData as NSData
        let stringData =  String(data: data,encoding: NSUTF8StringEncoding)
        print("After Operation: \(stringData)")
        return stringData!
    } else {
        print("Encryption Error: \(cryptStatus)")
    }
    return "";
}

推荐答案

加密数据将不是有效的 UTF-8 字符串,因为它应该与随机位无法区分.如果您需要以字符串形式使用它,则需要执行诸如 base64 编码或写出字节的十六进制值之类的操作.

The encrypted data will not be a valid UTF-8 string as it should be indistinguishable from random bits. If you need it in a string form you need to do something like base64 encode it or write out the hex values of the bytes.

NSData 有一个 base64EncodedDataWithOptions 方法,它应该产生一个字符串.

NSData has a base64EncodedDataWithOptions method which should produce a String.

这篇关于使用 CommonCrypto 的 Swift AES 加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆