CryptoSwift 加密的数据与 Node.js 不同
Data encrypted by CryptoSwift is not same as Node.js
我使用 CryptoSwift 加密了一些数据,然后使用 Node.js 加密了相同的数据。但是结果不一样。问了作者,他说不是bug
我不知道我哪里弄错了。这是我如何使用 CryptoSwift 和 Node.js:
的图片
密码算法:aes-256-cfb
key: 32 bytes 1
iv: 16 字节 0
CryptoSwift:开发分支 0.1.1
Node.js:长期支持 4.2.3
Data encrypted by Node.js 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 字节)的倍数并且数据大小为双方先验已知以满足要求填充是必需的。一般使用的padding是PKCS#7(PKCS#5本质上是一样的)
在代码中没有指定填充,所以块的余额将是缓冲区中的任何垃圾或者算法 可能 空填充它,最好不要依赖非标准默认值。
有关使用 Common Crypto 的示例,请参阅 SO Answer。
但最好的办法是使用 RNCryptor 进行加密,它适用于多种语言和平台。它还处理使加密安全的所有位。它已经过严格审查并正在积极开发中。
回答这个问题。
您的 NodeJS 代码加密 [0x5, 0x77, 0x5, 0x0, 0x3, 0x89, 0x20],但您的 CryptoSwift 代码加密 [0x5, 0x77],然后加密 [0x5, 0x0, 0x3, 0x89, 0x20]。这就是您得到不同结果的原因。
我使用 CryptoSwift 加密了一些数据,然后使用 Node.js 加密了相同的数据。但是结果不一样。问了作者,他说不是bug
我不知道我哪里弄错了。这是我如何使用 CryptoSwift 和 Node.js:
的图片密码算法:aes-256-cfb
key: 32 bytes 1
iv: 16 字节 0
CryptoSwift:开发分支 0.1.1
Node.js:长期支持 4.2.3
Data encrypted by Node.js 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 字节)的倍数并且数据大小为双方先验已知以满足要求填充是必需的。一般使用的padding是PKCS#7(PKCS#5本质上是一样的)
在代码中没有指定填充,所以块的余额将是缓冲区中的任何垃圾或者算法 可能 空填充它,最好不要依赖非标准默认值。
有关使用 Common Crypto 的示例,请参阅 SO Answer。
但最好的办法是使用 RNCryptor 进行加密,它适用于多种语言和平台。它还处理使加密安全的所有位。它已经过严格审查并正在积极开发中。
回答这个问题。
您的 NodeJS 代码加密 [0x5, 0x77, 0x5, 0x0, 0x3, 0x89, 0x20],但您的 CryptoSwift 代码加密 [0x5, 0x77],然后加密 [0x5, 0x0, 0x3, 0x89, 0x20]。这就是您得到不同结果的原因。