【问题标题】:Convert Aes.Key to SecureString in C#在 C# 中将 Aes.Key 转换为 SecureString
【发布时间】:2014-06-15 12:56:16
【问题描述】:

如何将 Aes.Key 转换为 secureString ?我正在做一个字节 [] -> 字符串 -> 安全字符串。我面临一个不同的问题。 将字节 [] 中的密钥转换为字符串并返回字节 [] 时,我得到一个不同的字节 []。代码有什么问题?

Aes aes = Aes.Create();
aes.GenerateIV();
aes.GenerateKey();

byte[] byteKey1 = aes.Key; 

string sKey = Encoding.UniCode.GetString(byteKey);
byte[] byteKey2= Encoding.UniCode.GetBytes(sKey);

“byteKey1”和“byteKey2”有时不同。如果我使用 Encoding.Default,它们是相等的,但是当不同的机器具有不同的默认编码时就会出现问题。

如何将 byte[] 中的 Key 转换为 SecureString 再转换回 byte[] ?

谢谢。

【问题讨论】:

    标签: c# encryption bytearray securestring


    【解决方案1】:

    切勿对加密密钥或密文等二进制数据使用文本编码(例如 Unicode 或 ASCII)。编码用于文本表示,实现可以在编码允许的范围内更改二进制内容。

    改为使用Convert.ToBase64StringConvert.FromBase64String 将二进制文本转换为可以以文本格式编码的形式。

    以下代码将说明byteKey2byteKey 将是相同的。

    string sKey = Convert.ToBase64String(byteKey);
    byte[] byteKey2= Convert.FromBase64String(sKey);
    bool equal = byteKey.SequenceEqual(byteKey2); // will be true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 2012-11-01
      相关资源
      最近更新 更多