這是我第一次嘗試,所以我不知道如果我需要的是用下面的代碼實現使用加密的加密字符串。CommonCrypto生成具有16字符長度
我的問題 - 我需要它生成一個16個字符的編碼字符串,而不是正在生成的64個字符。
我對使用本機迅速庫,而不是外部框架的偏好。因爲這個問題找不到如何使用CommonCrypto。不知道這是否正確。
在那裏我得到的例子
http://sketchytech.blogspot.co.nz/2016/02/resurrecting-commoncrypto-in-swift-for.html
我使用
let keyString = "1234567812345678"
let message = "12345678123456781234567812345678"
let iv = "iv-salt-string--" // string of 16 characters in length
let encoded = message.aesEncrypt(keyString, iv: iv)!
print("encoded -> \(encoded)")
let unencode = encoded.aesDecrypt(keyString, iv: iv)!
print("unencode -> \(unencode)")
輸出
encoded -> S81qV6F31xO8mUA1+HhsF7pHOMeE0f6Bbcmj3Zzk3EFLhQTCmfYlouorrUkYKL6K
unencode -> 12345678123456781234567812345678
擴展
extension String {
func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
data = self.dataUsingEncoding(NSUTF8StringEncoding),
cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyData.bytes, keyLength,
iv,
data.bytes, data.length,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
let base64cryptString = cryptData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
return base64cryptString
}
else {
return nil
}
}
return nil
}
func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
data = NSData(base64EncodedString: self, options: .IgnoreUnknownCharacters),
cryptData = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
let keyLength = size_t(kCCKeySizeAES128)
let operation: CCOperation = UInt32(kCCDecrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithmAES128)
let options: CCOptions = UInt32(options)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyData.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, encoding:NSUTF8StringEncoding)
return unencryptedMessage
}
else {
return nil
}
}
return nil
}
}