关于 AES 256 加密:
- 什么是公钥和私钥?
- 如何生成这两个密钥?
- 如何使用公众加密数据?
- 如何使用私有来解密数据?
在 .Net 中,您可以像这样创建密钥对:
public static Tuple<string, string> CreateKeyPair()
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams);
string publicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));
string privateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));
return new Tuple<string, string>(privateKey, publicKey);
}
然后,您可以使用您的公钥加密消息,如下所示:
public static byte[] Encrypt(string publicKey, string data)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(publicKey));
byte[] plainBytes = Encoding.UTF8.GetBytes(data);
byte[] encryptedBytes = rsaProvider.Encrypt(plainBytes, false);
return encryptedBytes;
}
并使用您的私钥进行解密,如下所示:
public static string Decrypt(string privateKey, byte[] encryptedBytes)
{
CspParameters cspParams = new CspParameters { ProviderType = 1 };
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams);
rsaProvider.ImportCspBlob(Convert.FromBase64String(privateKey));
byte[] plainBytes = rsaProvider.Decrypt(encryptedBytes, false);
string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
return plainText;
}
我认为你把事情搞混了。AES 是一种对称密码,因此只有一个密钥用于加密和解密。像 RSA 这样的非对称密码有两个密钥。用于加密的公钥和用于解密的私钥。