【问题标题】:AES GCM key derivation swiftAES GCM 密钥派生 swift
【发布时间】:2020-05-13 08:52:26
【问题描述】:

我正在尝试在swift 中实现与我在 java 中的代码等效的代码。基本上是带有GCM 填充的AES 实现,我为此使用了密钥派生。在swift 中,我使用的是CryptoSwift 库。

我的问题是我无法在swift 中获得相同的加密文本。 经过很长时间的研究,我找不到任何解决我的问题的方法,我什至看到了CryptoSwift 库存储库的测试代码以获得任何想法,但没有运气

这是我的java代码:

GCMParameterSpec ivParameterSpec = new GCMParameterSpec(128, "ivVector".getBytes());
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec("myPassword".toCharArray(), "salt".getBytes(), 1000, 256);
SecretKey tmp = secretKeyFactory.generateSecret(keySpec);
key = new SecretKeySpec(tmp.getEncoded(), "AES");
encryptCipher = Cipher.getInstance("AES/GCM/NoPadding");

encryptCipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
            byte[] encryptedWord = Base64.encode(encryptCipher.doFinal("example".getBytes("UTF-8")));

这是我的快速代码:

do{
    keyDerivation = try PKCS5.PBKDF2(password: "myPassword".bytes, salt: "salt".bytes, iterations: 1000, keyLength: 32, variant: .sha1).calculate()
    let gcm = GCM(iv: keyDerivation, mode: .combined)
    let aes = try AES(key: keyDerivation, blockMode: gcm, padding: .noPadding)
    let encryptedText = try aes.encrypt("example".bytes)

}catch{
    print(error)
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java swift cryptography aes-gcm cryptoswift


    【解决方案1】:

    您的 IV 在这两种情况下都不匹配。在 Java 中使用字符串,在 Swift 中使用keyDerivation 中的派生键。

    此外,您应该确保使用相同的字符编码。对于任何一种语言,我都不会使用 getBytes 或类似的。明确指定 UTF-8 可能是最好的。

    请注意,Java PBKDF2WithHmacSHA1 可能会以一种相当特殊的方式处理密码编码,因此可能需要对密码进行某种输入验证。

    不用说,每次加密调用的盐应该是随机的,而不是静态的。我想这只是测试代码。

    【讨论】:

    • 是的,你说得对,我的错。我在iv 中使用keyDerivation,我只是在swift 代码中为"ivVector" 更改了它,一切正常。是的,所有这些值都只是为了测试。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2018-05-31
    • 2015-06-17
    • 1970-01-01
    • 2012-11-02
    相关资源
    最近更新 更多