Untitled

mail@pastecode.io avatar
unknown
swift
6 months ago
1.8 kB
3
Indexable
Never
import Foundation
import CommonCrypto

enum AESError: Error {
    case keyError(String, Int)
    case cryptorError(String, Int)
}

// AES decryption in ECB mode
func aesECBDecrypt(data: Data, keyData: Data) throws -> Data? {
    let keyLength = keyData.count
    let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256]
    guard validKeyLengths.contains(keyLength) else {
        throw AESError.keyError("Invalid key length", keyLength)
    }

    let clearLength = size_t(data.count)
    var clearData = Data(count: clearLength)

    var numBytesDecrypted: size_t = 0
    let options = CCOptions(kCCOptionPKCS7Padding | kCCOptionECBMode)

    let cryptStatus = data.withUnsafeBytes { dataBytes -> CCCryptorStatus in
        clearData.withUnsafeMutableBytes { cryptBytes -> CCCryptorStatus in
            keyData.withUnsafeBytes { keyBytes -> CCCryptorStatus in
                CCCrypt(CCOperation(kCCDecrypt),
                        CCAlgorithm(kCCAlgorithmAES),
                        options,
                        keyBytes.baseAddress, keyLength,
                        nil, // No IV for ECB mode
                        dataBytes.baseAddress, clearLength,
                        cryptBytes.baseAddress, clearLength,
                        &numBytesDecrypted)
            }
        }
    }

    guard cryptStatus == CCCryptorStatus(kCCSuccess) else {
        throw AESError.cryptorError("Decryption failed", Int(cryptStatus))
    }

    clearData.count = numBytesDecrypted
    return clearData
}

// Example usage:
do {
    let encryptedData: Data = // Your encrypted data
    let keyData: Data = // Your key data (24 bytes for AES-192)
    if let decryptedData = try aesECBDecrypt(data: encryptedData, keyData: keyData) {
        // Use decryptedData
    }
} catch {
    print(error)
}
Leave a Comment