AES加密,示例代码

时间:2008-11-05 14:37:23

标签: encryption aes

如何在GUID上执行AES加密?

在客户端计算机上,我们将存储GUID及其公钥,我们的内部服务器将拥有私钥及其guid。

这是生成AES加密的所有必要输入吗?

3 个答案:

答案 0 :(得分:8)

AES是对称加密算法(加密和解密密钥相同)。如果您正在谈论公钥和私钥,则需要asymmetric encryption algorithm,例如RSA。

答案 1 :(得分:1)

您可以加密任何可以表示为字节流的内容。您问题中“食谱”中唯一缺少的成分是加密密钥:

void encrypt(char *plaintext, char *key, char *crypt)
{
  // Encrypt plaintext with the key, returning the result in crypt.

}

注意:

  • 使用PKI(公钥/私钥),每个参与者通常以安全的方式维护自己的私有密钥,并自由分发其 public 密钥。邮件使用收件人 public 密钥加密,并由每个收件人使用私有密钥解密。从问题的措辞来看,你使用这个模型并不明显。

  • Jesse为演示目的提供了一个很好的例子。请记住,您可能想要在生产应用程序中对密钥进行硬编码。

答案 2 :(得分:0)

这是使用AES(Rijndael)快速加密/解密字符串数据:

private static readonly byte[] rgbKey = Encoding.UTF8.GetBytes("Ni=9OE=$i+62eprIuDr@ewOu5I9r34Ro"); // change to your own secure key

private static readonly byte[] rgbIv = Encoding.UTF8.GetBytes("to$eO_e!maI*o3ut"); // change to your own secure initialization vector

public static string Encrypt(string originalString)
{
    if (string.IsNullOrEmpty(originalString))
    {
        throw new ArgumentNullException(
           "originalString",
           "The string which needs to be encrypted can not be null.");
    }

    using (var cryptoProvider = new RijndaelManaged())
    using (var memoryStream = new MemoryStream())
    using (var encryptor = cryptoProvider.CreateEncryptor(rgbKey, rgbIv))
    using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
    using (var writer = new StreamWriter(cryptoStream))
    {
        writer.Write(originalString);
        writer.Flush();
        cryptoStream.FlushFinalBlock();
        writer.Flush();
        return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
    }
}

public static string Decrypt(string encryptedString)
{
    if (string.IsNullOrEmpty(encryptedString))
    {
        throw new ArgumentNullException(
           "encryptedString",
           "The string which needs to be decrypted can not be null.");
    }

    using (var cryptoProvider = new RijndaelManaged())
    using (var memoryStream = new MemoryStream(Convert.FromBase64String(encryptedString)))
    using (var decryptor = cryptoProvider.CreateDecryptor(rgbKey, rgbIv))
    using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
    using (var reader = new StreamReader(cryptoStream))
    {
        return reader.ReadToEnd();
    }
}