問題描述
我需要創建一個長度為 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 的字節 []的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!