如何使用 FromBase64String 创建长度为 16 的字节 [] [英] How to create byte[] with length 16 using FromBase64String

查看:17
本文介绍了如何使用 FromBase64String 创建长度为 16 的字节 []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个长度为 16 的 byte[].(在 AES 加密中用作密钥的 128 位字节数组).

I have a requirement to create a byte[] with length 16. (A byte array that has 128 bit to be used as Key in AES encryption).

以下是一个有效的字符串

Following is a valid string

"AAECAwQFBgcICQoLDA0ODw=="

确定字符串是否为 128 位的算法是什么?还是只有反复试验才能创建这样的 128 位字符串?

What is the algorithm that determines whether a string will be 128 bit? Or is trial and error the only way to create such 128 bit strings?

代码

    static void Main(string[] args)
    {
        string firstString = "AAECAwQFBgcICQoLDA0ODw=="; //String Length = 24
        string secondString = "ABCDEFGHIJKLMNOPQRSTUVWX"; //String Length = 24
        int test = secondString.Length;

        byte[] firstByteArray = Convert.FromBase64String((firstString));
        byte[] secondByteArray = Convert.FromBase64String((secondString));

        int firstLength = firstByteArray.Length;
        int secondLength = secondByteArray.Length;


        Console.WriteLine("First Length: " + firstLength.ToString());
        Console.WriteLine("Second Length: " + secondLength.ToString());

        Console.ReadLine();
    }

调查结果:

对于 256 位,我们需要 256/6 = 42.66 个字符.这是四舍五入到 43 个字符.[要使其可被 4 整除,请添加 =]

For 256 bit, we need 256/6 = 42.66 chars. That is rounded to 43 char. [To make it divisible by 4 add =]

对于 512 位,我们需要 512/6 = 85.33 个字符.这是四舍五入到 86 个字符.[要使其可被 4 整除,请添加 ==]

For 512 bit, we need 512/6 = 85.33 chars. That is rounded to 86 char. [To make it divisible by 4 add ==]

对于 128 位,我们需要 128/6 = 21.33 个字符.这是四舍五入到 22 个字符.[要使其可被 4 整除,请添加 ==]

For 128 bit, we need 128/6 = 21.33 chars. That is rounded to 22 char. [To make it divisible by 4 add ==]

推荐答案

16 字节的 base64 字符串将始终为 24 个字符,并以 == 结尾,作为填充.

A base64 string for 16 bytes will always be 24 characters and have == at the end, as padding.

(至少当它可以使用 .NET 方法解码时.填充并不总是包含在所有 base64 字符串的使用中,但 .NET 实现需要它.)

(At least when it's decodable using the .NET method. The padding is not always inlcuded in all uses of base64 strings, but the .NET implementation requires it.)

这篇关于如何使用 FromBase64String 创建长度为 16 的字节 []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆