Encrypting a string using kCCAlgorithmAES

extension Data {
    func aes256Encrypt(withKey key: Data, iv: Data) -> Data? {
        if key.count != kCCKeySizeAES128 && key.count != kCCKeySizeAES192 && key.count != kCCKeySizeAES256 {
            return nil
        }
        if iv.count != kCCBlockSizeAES128 && iv.count != 0 {
            return nil
        }
        
        var result: Data?
        let bufferSize = self.count + kCCBlockSizeAES128
        var buffer = [UInt8](repeating: 0, count: bufferSize)
        var encryptedSize = 0
        
        let cryptStatus = key.withUnsafeBytes { keyBytes in
            return iv.withUnsafeBytes { ivBytes in
                return self.withUnsafeBytes { dataBytes in
                    return CCCrypt(
                        CCOperation(kCCEncrypt),
                        CCAlgorithm(kCCAlgorithmAES),
                        CCOptions(kCCOptionPKCS7Padding),
                        keyBytes.baseAddress,
                        key.count,
                        ivBytes.baseAddress,
                        dataBytes.baseAddress,
                        self.count,
                        &buffer,
                        bufferSize,
                        &encryptedSize
                    )
                }
            }
        }
        
        if cryptStatus == kCCSuccess {
            result = Data(bytes: buffer, count: encryptedSize)
        }
        
        return result
    }
}

You can use it as shown below

if let stringToEncrypt = "string to encrypt".data(using: .utf8), let secret = "secretKey", let secretData = secret.data(using: .utf8) {
                            let iv = String(secret.prefix(16))
                            guard let ivData = iv.data(using: .utf8) else {
                                return nil
                            }
                          if let encryptedData = stringToEncrypt.aes256Encrypt(withKey: secretData as Data, iv: ivData) {

Finally convert it back to the string

let sign = encryptedData.base64EncodedString()

In

,

Leave a Reply

Your email address will not be published. Required fields are marked *