CryptoSwiftencryption的数据与Node.js不同

我使用CryptoSwiftencryption一些数据,然后使用Node.jsencryption相同的数据。 但结果不一样。 我问作者,他说这不是一个错误。

我不知道我在哪里犯了一个错误。 这里是我如何使用CryptoSwift和Node.js的图片:

密码algorithm:aes-256-cfb

键:32字节1

iv:16个字节0

CryptoSwift:开发分支0.1.1

Node.js:LTS 4.2.3

由CryptoSwiftencryption的数据

由Node.jsencryption的数据4.2.3

这里是swift代码:

func testAES() { let key = [UInt8](count: 32, repeatedValue: 1) let iv = [UInt8](count: 16, repeatedValue: 0) print(key) print(iv) let aes256cfb = try! AES(key: key, iv: iv, blockMode: .CFB) let en1 = try! aes256cfb.encrypt([0x5, 0x77], padding: nil) print(en1.map({ i in String(format: "%2x", i)})) let en2 = try! aes256cfb.encrypt([0x5, 0x0, 0x3, 0x89, 0x20], padding: nil) print(en2.map({ i in String(format: "%2x", i)})) } CryptoSwift: ["77", "ef"] ["77", "98", "c9", "2c", "45"] Node.js: <Buffer 77 ef> <Buffer cf a5 66 8a 3e> 

你可以看到,前两个字节是相同的,但其余的不是。 为什么? 我的代码写错了吗? 我对密码不太了解,请告诉我原因。 非常感谢。

除非数据是块大小(16字节)的倍数,并且数据大小是双方都知道的,以满足要求填充是必需的。 通常使用的填充是PKCS#7(PKCS#5本质上是相同的)。

在代码中没有指定填充,所以块的平衡将是无论是在缓冲区中的垃圾,或者algorithm可能无效填充它,总是最好不要依靠非标准的默认值。

请参阅SO Answer有关使用Common Crypto的示例。

但最好的办法是使用RNCryptor进行encryption,它可用于多种语言和平台。 它还处理使encryption安全的所有位。 经过严格审查和积极开发。

回答这个问题。

你的NodeJS代码encryption[0x5,0x77,0x5,0x0,0x3,0x89,0x20],但你的CryptoSwift代码encryption[0x5,0x77]然后[0x5,0x0,0x3,0x89,0x20]。 这就是为什么你得到不同的结果。