gpt4 book ai didi

.net - 使用 CCKeyDerivationPBKDF 获取派生 key

转载 作者:行者123 更新时间:2023-11-30 12:21:16 24 4
gpt4 key购买 nike

我在使用 CCKeyDerivationPBKDF 获取伪随机生成的派生 key 时遇到问题。

这是我使用的 @zaph 代码:

//    password     password String
// salt salt Data
// keyByteCount number of key bytes to generate
// rounds Iteration rounds
//
// returns Derived key


func pbkdf2SHA1(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA1), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA256(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2SHA512(password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
return pbkdf2(hash:CCPBKDFAlgorithm(kCCPRFHmacAlgSHA512), password:password, salt:salt, keyByteCount:keyByteCount, rounds:rounds)
}

func pbkdf2(hash :CCPBKDFAlgorithm, password: String, salt: Data, keyByteCount: Int, rounds: Int) -> Data? {
let passwordData = password.data(using:String.Encoding.utf8)!
var derivedKeyData = Data(repeating:0, count:keyByteCount)

let derivationStatus = derivedKeyData.withUnsafeMutableBytes {derivedKeyBytes in
salt.withUnsafeBytes { saltBytes in

CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
password, passwordData.count,
saltBytes, salt.count,
hash,
UInt32(rounds),
derivedKeyBytes, derivedKeyData.count)
}
}

if (derivationStatus != 0) {
print("Error: \(derivationStatus)")
return nil;
}



return derivedKeyData
}

我的问题是它不断为每次调用生成相同的派生 key 。我正在尝试使用 Rfc2898DeriveBytes 解密在 .Net 端加密的数据:

var saltBytes = Encoding.ASCII.GetBytes(salt);
var key = new Rfc2898DeriveBytes(Inputkey, saltBytes);

var aesAlg = new RijndaelManaged();
aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8); // default keySize 256
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); // default blockSize 128

在 .Net 方面,Rfc2898DeriveBytes 返回新的随机字节集,但我的 Swift 代码仅为每个调用生成相同的序列。Swift 端的序列生成有什么问题?

Edit1:当我在 Swift 中使用来自 .net 的 Rfc2898DeriveBytes 生成的 Key 和 IV 的字节序列尝试解密 .net 中加密的数据时,它工作正常。

Edit2:好的,我发现 Rfc2898DeriveBytes 第一次使用 GetBytes 方法时的结果与 Swift PBKDF2 结果相同。第二次调用 GetBytes 给出了完全不同的结果。这是为什么?如果我能解决这个问题,那么我的解密应该可以工作。

aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);   // (1) - the same result as in Swift implementation
aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8); // (2) - completly different result

我在 Swift 中初始化 IV 是否错误?

最佳答案

.NET 实现实际上是一个流。要从 Apple 版本获得等效答案,您应该询问一次调用中所需的总字节数,然后将其分成您需要的任何部分。

关于.net - 使用 CCKeyDerivationPBKDF 获取派生 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762842/

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