首页 > 解决方案 > 这种加密方法对于 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;
}

标签: c#encryption.net-core

解决方案


Well, it's just RSA / PKCS#1 v1.5 encryption. In principle you'd better use OAEP because it is:

  1. provable secure and
  2. 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.


推荐阅读