在该方法的正式描述中,Microsoft在以下链接中说明MachineKey.Protect“通过加密或签名来保护指定的数据”:https://msdn.microsoft.com/en-us/library/system.web.security.machinekey.protect(v=vs.110).aspx
这是什么意思?它如何决定加密,签名或两者兼而有之?
最佳答案
MSDN documentation或.NET Web Development and Tools Blog都没有确切说明它是如何工作的,但是this article提到MachineKey API会完成这两项操作(顺便说一句,它更安全)。
我对.NET参考源进行了更深入的研究,显然这是事实。看看这段代码:
using (ICryptoTransform encryptor = encryptionAlgorithm.CreateEncryptor()) {
using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write)) {
cryptoStream.Write(clearData, 0, clearData.Length);
cryptoStream.FlushFinalBlock();
// At this point:
// memStream := IV || Enc(Kenc, IV, clearData)
// These KeyedHashAlgorithm instances are single-use; we wrap it in a 'using' block.
using (KeyedHashAlgorithm signingAlgorithm = _cryptoAlgorithmFactory.GetValidationAlgorithm()) {
// Initialize the algorithm with the specified key
signingAlgorithm.Key = _validationKey.GetKeyMaterial();
// Compute the signature
byte[] signature = signingAlgorithm.ComputeHash(memStream.GetBuffer(), 0, (int)memStream.Length);
// At this point:
// memStream := IV || Enc(Kenc, IV, clearData)
// signature := Sign(Kval, IV || Enc(Kenc, IV, clearData))
// Append the signature to the encrypted payload
memStream.Write(signature, 0, signature.Length);
// At this point:
// memStream := IV || Enc(Kenc, IV, clearData) || Sign(Kval, IV || Enc(Kenc, IV, clearData))
// Algorithm complete
byte[] protectedData = memStream.ToArray();
return protectedData;
}
}
}
这来自NetFXCryptoService,这是默认的加密提供程序,以防您未配置DataProtector