为什么编码后的密钥不等于原始密钥?

Why isn't the encoded key equal to the original key?

语言: C#,框架:.NET Core 3.1

我正在使用基于 AES 的加密。

研究:
Key Format AES

Gilles: An AES key is just a bunch of bits with no structure.

需要保存Key和IV,因为每次都是随机生成的,加解密需要用到

出于特殊原因,我需要将其存储为字符串,因此我希望能够将字节数组转换为字符串,并在需要时使用编码向后转换。

转换使用 UTF-8 编码进行。

我的问题:
我在我的代码中放置了一个断点,字节数组的内容与原始数组明显不同。我试过切换到其他编码格式,但这也失败了。简而言之,数据已更改,这将导致无法解密消息,因为 AES 密钥和 IV 不正确。

更新:
keyBytes 不包含有效的 utf8 数据时,UTF-8 转换不起作用,编码器将生成导致问题的回退数据。

示例:

using (Aes myAes = Aes.Create())
{
    bool valid = false;
    byte[] keyBytes = myAes.Key;
    Encoding utf8WithoutBom = new UTF8Encoding(true);

    string key = utf8WithoutBom.GetString(keyBytes);
    byte[] outputBytes = utf8WithoutBom.GetBytes(key);

    if (myAes.Key.Length == outputBytes.Length) {
        for (int i = 0; i < myAes.Key.Length; i++) {
            if (outputBytes[i] == keyBytes[i]) {
                valid = true;
            }

            else {
                valid = false;
                break;
            }
        }
    }

    if (valid == true) {
        Console.WriteLine("Succes");
    }

    else {
        Console.WriteLine("Error");
        throw new Exception("The keys do not match.");
    }
}

结果:
- 输出:byte[] 大小在 50~54 Error
之间 - 期望的输出:byte[32] 与原始数组 Succes

具有相同的数据

问题:
为什么输出字节数组的内容和原来的字节数组不一样?

只有当初始字节数组包含有效的 utf8 内容时,byte[] -> string -> byte[] 的转换才会起作用。并非每个 32 字节数组都这样做。

如果原始数组包含无效数据,byte[] -> string 转换已经 return 一些后备数据,第二次转换会将这些后备值转换为相应的字节。

如果要将任意字节数组编码为字符串,请使用 Base64 或其他一些通用数据编码,但不能使用 utf8。