在 ECB 模式下解密 AES

Decrypt AES in ECB mode

我正在尝试解密一个简单的框架:

uint8_t chipertext[] = {0x72, 0x82, 0xC9, 0xAA, 0x1F, 0xE1, 0x84, 0x97, 0x06, 0x65, 0x58, 0x5D, 0x06, 0x7B, 0xD4, 0xB4};

已使用以下密钥加密:

uint8_t aes_key[]    = {0x0A, 0x1A, 0x2A, 0x3A, 0x0B, 0x1B, 0x2B, 0x3B, 0x0C, 0x1C, 0x2C, 0x3C, 0x0D, 0x1D, 0x2D, 0x3D};

我知道结果会是(明文):

uint8_t plaintext[]  = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};

在我的 swift 代码下方:

将加密消息转换为字符串:

let hexString = "0x72,0x82,0xC9,0xAA,0x1F,0xE1,0x84,0x97,0x06,0x65,0x58,0x5D,0x06,0x7B,0xD4,0xB4"
// Remove all of the "0x"
let cleanString = hexString.replacingOccurrences(of: "0x", with: "")
// Create an array of hex strings
let hexStrings = cleanString.components(separatedBy: ",")
// Convert the array of hex strings into bytes (UInt8)
let bytes = hexStrings.compactMap { UInt8([=13=], radix: 16) }

let datar = String(decoding: bytes, as: UTF8.self)
let datas = Data(datar.utf8)
let datarToString = String(data: datas, encoding: String.Encoding.utf8)!

将密钥转换为字符串:

 let hexStringKey = "0x0A,0x1A,0x2A,0x3A,0x0B,0x1B,0x2B,0x3B,0x0C,0x1C,0x2C,0x3C,0x0D,0x1D,0x2D,0x3D"
 // Remove all of the "0x"
 let cleanStringKey = hexStringKey.replacingOccurrences(of: "0x", with: "")
 // Create an array of hex strings
 let hexStringsKey = cleanStringKey.components(separatedBy: ",")
 // Convert the array of hex strings into bytes (UInt8)
 let bytesKey = hexStringsKey.compactMap { UInt8([=14=], radix: 16) }

 let datarKey = String(decoding: bytesKey, as: UTF8.self)
 let datasKey = Data(datarKey.utf8)
 let datarToStringKey = String(data: datasKey, encoding: String.Encoding.utf8)!

然后我使用 CryptoSwift 执行 AES 解密功能:

func decrypt(cryptedMessage: String , key:String) -> String? {
        var clearMessage:String? = nil;

        let cryptedData = Data(cryptedMessage.data(using: .utf8)!)

        do {
            let aes = try AES(key: Array<UInt8>(key.utf8), blockMode: ECB(), padding: .noPadding) // aes128
            let cipher = try aes.decrypt(Array<UInt8>(cryptedData))
            clearMessage = String(bytes: cipher, encoding: .utf8)
        } catch {
            let error = error as NSError
            print(error)
        }

        return clearMessage
    }

我的问题是当我尝试像这样获取解密消息时:

let cryptedMessage = datarToString.decryptAES(key: datarToStringKey)

我得到:Error: invalidData

如果有人有想法我不明白我哪里做错了。我确定 ECB 模式和 noPadding 选项。

谢谢!

您不能将任意数据转换为 UTF-8 字符串。这些行无效,您很幸运,它们没有崩溃。

let datarToString = String(data: datas, encoding: String.Encoding.utf8)!
let datarToStringKey = String(data: datasKey, encoding: String.Encoding.utf8)!

同样,您不应将字符串传递给 decrypt。只需传递密文和密钥的数据即可。