AES(Advanced Encryption Standard)是一种对称加密算法,广泛用于数据加密。CBC(Cipher Block Chaining)是AES的一种工作模式,它将每个明文块与前一个密文块进行异或运算后再加密,从而提高安全性。PKCS5(Padding Scheme 5)是一种填充方案,用于确保数据长度符合加密算法的要求。
在iOS中,可以使用CommonCrypto库来实现AES加密和解密。以下是一个示例代码:
import CommonCrypto
func encrypt(data: Data, key: Data, iv: Data) -> Data? {
var encryptedData = Data(count: data.count + kCCBlockSizeAES128)
var encryptedDataLength: Int = 0
let status = encryptedData.withUnsafeMutableBytes { encryptedBytes in
data.withUnsafeBytes { dataBytes in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCEncrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes.baseAddress, key.count,
ivBytes.baseAddress,
dataBytes.baseAddress, data.count,
encryptedBytes.baseAddress, encryptedData.count,
&encryptedDataLength)
}
}
}
}
if status == kCCSuccess {
encryptedData.count = encryptedDataLength
return encryptedData
}
return nil
}
func decrypt(data: Data, key: Data, iv: Data) -> Data? {
var decryptedData = Data(count: data.count + kCCBlockSizeAES128)
var decryptedDataLength: Int = 0
let status = decryptedData.withUnsafeMutableBytes { decryptedBytes in
data.withUnsafeBytes { dataBytes in
key.withUnsafeBytes { keyBytes in
iv.withUnsafeBytes { ivBytes in
CCCrypt(CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES),
CCOptions(kCCOptionPKCS7Padding),
keyBytes.baseAddress, key.count,
ivBytes.baseAddress,
dataBytes.baseAddress, data.count,
decryptedBytes.baseAddress, decryptedData.count,
&decryptedDataLength)
}
}
}
}
if status == kCCSuccess {
decryptedData.count = decryptedDataLength
return decryptedData
}
return nil
}
通过以上步骤,你可以在iOS中实现AES/CBC/PKCS5的加密和解密。如果遇到问题,请检查密钥、IV和数据长度是否符合要求,并确保使用正确的填充方案。
领取专属 10元无门槛券
手把手带您无忧上云