iOS Swift vs Node JS Crypto不同的输出

时间:2016-04-29 09:01:25

标签: ios node.js swift encryption

我不确定我的Node JS代码有什么问题。 Node JS的输出缺少一些字符而不是iOS Swift中的输出。

我的节点JS代码:

var crypto              = require('crypto');

var CRYPTO_ALGORITHM    = "aes-256-ctr";
var CRYPTO_PASSWORD     = "3zTvzr3p67VC61jmV54rIYu1545x4TlY";
var CRYPTO_IV           = "0123456789012345";

var string_data = "OLIVER MARTINEZ OLIVER";

var cipher      = crypto.createCipheriv(CRYPTO_ALGORITHM, CRYPTO_PASSWORD, CRYPTO_IV);
var encrypted   = cipher.update(string_data, "utf8", "hex");
encrypted       += cipher.final("hex"); // to hex

console.log("encrypted final: " + encrypted);

// --------------------------------------------------------------- //

var encrypted_string = encrypted;

var decipher    = crypto.createDecipheriv(CRYPTO_ALGORITHM, CRYPTO_PASSWORD, CRYPTO_IV);
var decrypted   = decipher.update(encrypted_string, "hex", "utf8"); 
decrypted       += decipher.final("utf8"); // to utf8

console.log("decrypted final: " + decrypted);

NODE OUTPUT:3df3cfd9adef86489fd27629d75f3fcbb744e5bae846

我的iOS Swift代码:

let CRYPTO_IV           = "0123456789012345";
let CRYPTO_PASSWORD     = "3zTvzr3p67VC61jmV54rIYu1545x4TlY";

let data                = "OLIVER MARTINEZ OLIVER";

let encrypted = try! data.encrypt(AES(key: CRYPTO_PASSWORD, iv: CRYPTO_IV, blockMode: .CTR)).toHexString();

print("encrypted: \(encrypted)");

IOS SWIFT OUTPUT:3df3cfd9adef86489fd27629d75f3fcbb744e5bae846bde7df9e98571ba27f01

如你所见。输出非常相似。只有NodeJS输出缺少一些字符。

1 个答案:

答案 0 :(得分:1)

CTR mode是一种流媒体模式,不需要任何填充。似乎CryptoSwift总是添加填充,即使使用像CTR这样的流模式。您需要请求在Swift中不应用填充:

data.encrypt(AES(key: CRYPTO_PASSWORD, iv: CRYPTO_IV, blockMode: .CTR, padding: NoPadding())).toHexString();