gpt4 book ai didi

swift - 在 Swift 中反向 CRC-32 NSData

转载 作者:行者123 更新时间:2023-11-28 08:51:21 24 4
gpt4 key购买 nike

我认为答案的组成部分就在那里,但我对这些东西的理解还不够好,而且我在转换方面遇到了很大的困难。

这是我找到的 NSData 到 crc32 的实现:

https://github.com/krzyzanowskim/CryptoSwift/blob/643bbabd6781b6e226f18815dba616cf6a08629b/CryptoSwift/CRC.swift

不幸的是,我需要一个有反转的版本:

这个线程似乎最接近:Reversing CRC32

我已经使用它的逻辑来创建生成两个 CRC 表的逻辑:

func crcTables() -> (forwardTable: [UInt32], reverseTable: [UInt32]) {
let poly: UInt32 = 0xedb88320;

var forwardTable: [UInt32] = []
var reverseTable: [UInt32] = []

var forward: UInt32 = 0
var reverse: UInt32 = 0
for i in 0...UInt32(UInt8.max) {
forward = i
reverse = i << (3 * 8)

for _ in 1...8 {
if (forward & 1) == 1 {
forward = (forward >> 1) ^ poly
} else {
forward >>= 1
}

if (reverse & 0x80000000) != 0 {
reverse = ((reverse ^ poly) << 1) | 1
} else {
reverse <<= 1
}
}

forwardTable.append(forward)
reverseTable.append(reverse)
}

return (forwardTable, reverseTable)
}

但是,现在我非常困惑如何获取数据并创建反向 crc32:

func reverseCRC(data: NSData) -> UInt32 {
var bytes = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&bytes, length:data.length * sizeof(UInt8))


return 0
}

更新

通过各种搜索,我想出了这个:

func reverseCRC32WithData(data: NSData, wantedCRC: UInt32 = 0) -> UInt32 {
var reversedCRC = wantedCRC

var bytes = [UInt8](count: data.length, repeatedValue: 0)
data.getBytes(&bytes, length:data.length * sizeof(UInt8))

// Drop trailing 1 if exists
let bufferLength = (data.length >> 1) << 1

for i in 0.stride(to: bufferLength + 4, by: sizeof(UInt16)) {
var word: UInt16 = 0x0000
if i < bufferLength {
let b1 = bytes[bufferLength - 2 - i]
let b2 = bytes[bufferLength - 1 - i]
word = (UInt16(b1) << 8) | UInt16(b2)
} else {
word = 0xffff
}

reversedCRC = ((reversedCRC << 8) & 0xffffffff) ^ ReverseTable[Int((reversedCRC >> 24) & 0xff)] ^ (UInt32(word) >> 8) & 0xff
reversedCRC = ((reversedCRC << 8) & 0xffffffff) ^ ReverseTable[Int((reversedCRC >> 24) & 0xff)] ^ (UInt32(word) & 0xff)
}

return reversedCRC
}

但是,我并不真正理解它(尤其是最后两行),而且我不确定如何测试它的准确性。如果有人可以朝这个方向提供帮助。

目标

我有一个固件更新,我正在通过蓝牙传输到硬件,一旦固件更新的所有数据都已传输,我将以以下形式提交验证有效负载:

Reversed CRC 32 (Big Endian)

最佳答案

我刚从 Apple Document 找到这个答案,

就我而言,它对我有用,

let CRC32_UInt32 = CRC32.checksum(bytes: inputBytes) // 73DECCF1
let reverse_CRC32_UInt32 = CFSwapInt32(CRC32_UInt32)
let reverse_crc32 = String(reverse_CRC32_UInt32, radix: 16, uppercase: true) // F1CCDE73

CRC32算法如下:

class CRC32 {

static var table: [UInt32] = {
(0...255).map { i -> UInt32 in
(0..<8).reduce(UInt32(i), { c, _ in
(c % 2 == 0) ? (c >> 1) : (0xEDB88320 ^ (c >> 1))
})
}
}()

static func checksum(bytes: [UInt8]) -> UInt32 {
return ~(bytes.reduce(~UInt32(0), { crc, byte in
(crc >> 8) ^ table[(Int(crc) ^ Int(byte)) & 0xFF]
}))
}
}

希望这对任何需要的人都有帮助😀

关于swift - 在 Swift 中反向 CRC-32 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34141142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com