gpt4 book ai didi

c# - 如何在 C# 中创建受密码保护的文件

转载 作者:太空狗 更新时间:2023-10-30 00:17:39 24 4
gpt4 key购买 nike

this 有点互补,但绝非相同问题。

如何创建受密码保护的文件?

最佳答案

加密:

private const int SaltSize = 8;

public static void Encrypt( FileInfo targetFile, string password )
{
var keyGenerator = new Rfc2898DeriveBytes( password, SaltSize );
var rijndael = Rijndael.Create();

// BlockSize, KeySize in bit --> divide by 8
rijndael.IV = keyGenerator.GetBytes( rijndael.BlockSize / 8 );
rijndael.Key = keyGenerator.GetBytes( rijndael.KeySize / 8 );

using( var fileStream = targetFile.Create() )
{
// write random salt
fileStream.Write( keyGenerator.Salt, 0, SaltSize );

using( var cryptoStream = new CryptoStream( fileStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write ) )
{
// write data
}
}
}

并解密:

public static void Decrypt( FileInfo sourceFile, string password )
{
// read salt
var fileStream = sourceFile.OpenRead();
var salt = new byte[SaltSize];
fileStream.Read( salt, 0, SaltSize );

// initialize algorithm with salt
var keyGenerator = new Rfc2898DeriveBytes( password, salt );
var rijndael = Rijndael.Create();
rijndael.IV = keyGenerator.GetBytes( rijndael.BlockSize / 8 );
rijndael.Key = keyGenerator.GetBytes( rijndael.KeySize / 8 );

// decrypt
using( var cryptoStream = new CryptoStream( fileStream, rijndael.CreateDecryptor(), CryptoStreamMode.Read ) )
{
// read data
}
}

关于c# - 如何在 C# 中创建受密码保护的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740837/

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