我正在使用常见的加密和解密。 我正在使用AES进行API调用和响应。
我做对了所有事情,但是每当我解密 收到响应,只有响应中的第一个键无法获得 解密,其余的其他响应字符串则以良好的格式解密。
解密后的响应:
AES结构代码:
struct AES {
// MARK: - Value
// MARK: Private
private let key: Data
private let iv: Data
// MARK: - Initialzier
init?(key: String, iv: String) {
guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
debugPrint("Error: Failed to set a key.")
return nil
}
guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
debugPrint("Error: Failed to set an initial vector.")
return nil
}
self.key = keyData
self.iv = ivData
}
// MARK: - Function
// MARK: Public
func encrypt(string: String) -> String? {
let data = crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt))
let str = data?.base64EncodedString()
let ivStr = UIConstants.IV.base64Encoded
let str1 = (str?.replacingOccurrences(of: " ", with: ""))! + ":" + ivStr!
let str2 = str1.replacingOccurrences(of: "+", with: ".")
let str3 = str2.replacingOccurrences(of: "/", with: "_")
let str4 = str3.replacingOccurrences(of: "=", with: "-")
let str5 = str4.replacingOccurrences(of: "\n", with: "")
return str5
}
func decrypt(data: Data?) -> String? {
guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil }
return String(bytes: decryptedData, encoding: .ascii)
}
func crypt(data: Data?, option: CCOperation) -> Data? {
guard let data = data else { return nil }
let cryptLength = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128).count
var cryptData = Data(count: cryptLength)
let keyLength = [UInt8](repeating: 0, count: kCCBlockSizeAES128).count
let options = CCOptions(kCCOptionPKCS7Padding)
var bytesLength = Int(0)
let status = cryptData.withUnsafeMutableBytes { cryptBytes in
data.withUnsafeBytes { dataBytes in
iv.withUnsafeBytes { ivBytes in
key.withUnsafeBytes { keyBytes in
CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes, keyLength, ivBytes, dataBytes, data.count, cryptBytes, cryptLength, &bytesLength)
}
}
}
}
guard UInt32(status) == UInt32(kCCSuccess) else {
debugPrint("Error: Failed to crypt data. Status \(status)")
return nil
}
cryptData.removeSubrange(bytesLength..<cryptData.count)
return cryptData
}
}
API响应解密代码:
let responseDic = response.object! as [String: Any]
let responseString = responseDic["data"] as! String
let str2 = responseString.replacingOccurrences(of: ".", with: "+")
let str3 = str2.replacingOccurrences(of: "_", with: "/")
let str4 = str3.replacingOccurrences(of: "-", with: "=")
let index = str4.range(of: ":")?.lowerBound
let substring = str4[..<index!]
let stringRemovingIV = String(substring)
print(stringRemovingIV)
let data = Data(base64Encoded: stringRemovingIV, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
var decryptString = aes256?.decrypt(data: data) as! String
print(decryptString)
let responseObject = NSDictionary.convertStringToDictionary(text: String(decryptString))
print(responseObject as Any)