c# - 这种加密方法对于 Windows 应用程序是否安全?
问题描述
我正在创建一个库来执行一些使用 OAuth2 的 REST API 调用。我想缓存刷新令牌,这样用户就不必在每次登录时重新进行身份验证,尽管我对密码学几乎一无所知。Microsoft Docs 表示,对于像字符串这样的小块数据,非对称加密是可行的方法。这是我的课程,用于将加密令牌存储在计算机某处的文件中(由调用代码指定)。它有效,我只是不确定它有多安全。
string _file;
const string _containerName = "MyTokenCache";
public EncryptedTokenCache(string fileLocation)
{
_file = fileLocation;
}
public void SaveToken(string token)
{
var rsa = CreateRSAProvider(_containerName);
var encryptedData = rsa.Encrypt(Encoding.UTF8.GetBytes(token), RSAEncryptionPadding.Pkcs1);
WriteToFile(encryptedData);
}
public string GetToken()
{
var rsa = CreateRSAProvider(_containerName);
var encryptedData = ReadFromFile();
var decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);
return Encoding.UTF8.GetString(decryptedData);
}
private RSA CreateRSAProvider(string containerName)
{
CspParameters parameters = new CspParameters
{
KeyContainerName = containerName
};
return new RSACryptoServiceProvider(parameters);
}
private void WriteToFile(byte[] data)
{
using(var fs = new FileStream(_file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
fs.Write(data, 0, data.Length);
}
}
private byte[] ReadFromFile()
{
byte[] data;
using (var fs = new FileStream(_file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
{
data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
}
return data;
}
解决方案
Well, it's just RSA / PKCS#1 v1.5 encryption. In principle you'd better use OAEP because it is:
- provable secure and
- less vulnerable to padding oracle attacks.
But for storing tokens PKCS#1 v1.5 should be fine.
Furthermore, you could use symmetric encryption using AES as well, as you currently create the key pair each time you create your class. That means that the private key is available at the same location as the public key, so the security that asymmetric crypto brings is not directly used. That said, I don't see any pressing need to use AES instead for this particular use case.
推荐阅读
- r - R如何将字符串拆分为向量,以便向量中的每个位置对应一个字母
- linux - 在Linux中的每一列后面粘贴第一行
- ios - 对从 nib 加载的子视图应用阴影
- python - Python 和 R - 比较打印变量
- r - 将数据 modis EVI 转换为 r 中的日期 yy-mm-dd
- javascript - 我可以在返回的文档中使用 mongoose 进行查询吗?
- java - eclipse 在 ManagedBean 中看不到创建的类
- authentication - 使用多个域的 Kerberos 登录
- r - 使用双 for 循环访问 r 中数据帧中的元素
- java - JSTL JSP 包含 Servlet 使 JSP 空白