簡體   English   中英

如何將字節數組(MD5哈希)轉換為字符串(36個字符)?

[英]How to convert a byte array (MD5 hash) into a string (36 chars)?

我有一個使用哈希函數創建的字節數組。 我想將此數組轉換為字符串。 到目前為止這么好,它會給我十六進制字符串。

現在我想使用不同於十六進制字符的東西,我想用這36個字符編碼字節數組 :[az] [0-9]

我該怎么辦?

編輯:我之所以這樣做,是因為我希望有一個比十六進制字符串更小的字符串。

我將這個任意長度的基本轉換函數從這個答案改編為C#:

static string BaseConvert(string number, int fromBase, int toBase)
{
    var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
    var length = number.Length;
    var result = string.Empty;

    var nibbles = number.Select(c => digits.IndexOf(c)).ToList();
    int newlen;
    do {
        var value = 0;
        newlen = 0;

        for (var i = 0; i < length; ++i) {
            value = value * fromBase + nibbles[i];
            if (value >= toBase) {
                if (newlen == nibbles.Count) {
                    nibbles.Add(0);
                }
                nibbles[newlen++] = value / toBase;
                value %= toBase;
            }
            else if (newlen > 0) {
                if (newlen == nibbles.Count) {
                    nibbles.Add(0);
                }
                nibbles[newlen++] = 0;
            }
        }
        length = newlen;
        result = digits[value] + result; //
    }
    while (newlen != 0);

    return result;
}

由於它來自PHP,它可能不是太慣用的C#,也沒有參數有效性檢查。 但是,您可以為它提供一個十六進制編碼的字符串,它可以正常工作

var result = BaseConvert(hexEncoded, 16, 36);

這不完全是你要求的,但將byte[]編碼為hex是微不足道的。

看到它在行動

今晚早些時候,我遇到了一個代碼轉換問題,圍繞着這里討論的相同算法。 請參閱: https//codereview.stackexchange.com/questions/14084/base-36-encoding-of-a-byte-array/

我提供了其早期答案之一的改進實現(都使用BigInteger)。 請參閱: https//codereview.stackexchange.com/a/20014/20654 解決方案采用byte []並返回Base36字符串。 原始和我的都包括簡單的基准信息。

為了完整起見,以下是從字符串解碼byte []的方法。 我還將包含上面鏈接中的編碼功能。 有關解碼的一些簡單基准信息,請參閱此代碼塊后面的文本。

const int kByteBitCount= 8; // number of bits in a byte
// constants that we use in FromBase36String and ToBase36String
const string kBase36Digits= "0123456789abcdefghijklmnopqrstuvwxyz";
static readonly double kBase36CharsLengthDivisor= Math.Log(kBase36Digits.Length, 2);
static readonly BigInteger kBigInt36= new BigInteger(36);

// assumes the input 'chars' is in big-endian ordering, MSB->LSB
static byte[] FromBase36String(string chars)
{
    var bi= new BigInteger();
    for (int x= 0; x < chars.Length; x++)
    {
        int i= kBase36Digits.IndexOf(chars[x]);
        if (i < 0) return null; // invalid character
        bi *= kBigInt36;
        bi += i;
    }

    return bi.ToByteArray();
}

// characters returned are in big-endian ordering, MSB->LSB
static string ToBase36String(byte[] bytes)
{
    // Estimate the result's length so we don't waste time realloc'ing
    int result_length= (int)
        Math.Ceiling(bytes.Length * kByteBitCount / kBase36CharsLengthDivisor);
    // We use a List so we don't have to CopyTo a StringBuilder's characters
    // to a char[], only to then Array.Reverse it later
    var result= new System.Collections.Generic.List<char>(result_length);

    var dividend= new BigInteger(bytes);
    // IsZero's computation is less complex than evaluating "dividend > 0"
    // which invokes BigInteger.CompareTo(BigInteger)
    while (!dividend.IsZero)
    {
        BigInteger remainder;
        dividend= BigInteger.DivRem(dividend, kBigInt36, out remainder);
        int digit_index= Math.Abs((int)remainder);
        result.Add(kBase36Digits[digit_index]);
    }

    // orientate the characters in big-endian ordering
    result.Reverse();
    // ToArray will also trim the excess chars used in length prediction
    return new string(result.ToArray());
}

“測試1234.做得稍大!” 編碼為Base64為“165kkoorqxin775ct82ist5ysteekll7kaqlcnnu6mfe7ag7e63b5”

解碼那個Base36字符串1,000,000次在我的機器上需要12.6558909秒(我使用了與我在codereview上的答案中提供的相同的構建和機器條件)

你提到你正在處理MD5哈希的byte [],而不是它的十六進制字符串表示,所以我認為這個解決方案為你提供了最少的開銷。

如果你想要一個更短的字符串並且可以接受[a-zA-Z0-9]和+和/然后看看Convert.ToBase64String

使用BigInteger(需要System.Numerics參考)

使用BigInteger(需要System.Numerics參考)

const string chars = "0123456789abcdefghijklmnopqrstuvwxyz";

// The result is padded with chars[0] to make the string length
// (int)Math.Ceiling(bytes.Length * 8 / Math.Log(chars.Length, 2))
// (so that for any value [0...0]-[255...255] of bytes the resulting
// string will have same length)
public static string ToBaseN(byte[] bytes, string chars, bool littleEndian = true, int len = -1)
{
    if (bytes.Length == 0 || len == 0)
    {
        return String.Empty;
    }

    // BigInteger saves in the last byte the sign. > 7F negative, 
    // <= 7F positive. 
    // If we have a "negative" number, we will prepend a 0 byte.
    byte[] bytes2;

    if (littleEndian)
    {
        if (bytes[bytes.Length - 1] <= 0x7F)
        {
            bytes2 = bytes;
        }
        else
        {
            // Note that Array.Resize doesn't modify the original array,
            // but creates a copy and sets the passed reference to the
            // new array
            bytes2 = bytes;
            Array.Resize(ref bytes2, bytes.Length + 1);
        }
    }
    else
    {
        bytes2 = new byte[bytes[0] > 0x7F ? bytes.Length + 1 : bytes.Length];

        // We copy and reverse the array
        for (int i = bytes.Length - 1, j = 0; i >= 0; i--, j++)
        {
            bytes2[j] = bytes[i];
        }
    }

    BigInteger bi = new BigInteger(bytes2);

    // A little optimization. We will do many divisions based on 
    // chars.Length .
    BigInteger length = chars.Length;

    // We pre-calc the length of the string. We know the bits of 
    // "information" of a byte are 8. Using Log2 we calc the bits of 
    // information of our new base. 
    if (len == -1)
    {
        len = (int)Math.Ceiling(bytes.Length * 8 / Math.Log(chars.Length, 2));
    }

    // We will build our string on a char[]
    var chs = new char[len];
    int chsIndex = 0;

    while (bi > 0)
    {
        BigInteger remainder;
        bi = BigInteger.DivRem(bi, length, out remainder);

        chs[littleEndian ? chsIndex : len - chsIndex - 1] = chars[(int)remainder];
        chsIndex++;

        if (chsIndex < 0)
        {
            if (bi > 0)
            {
                throw new OverflowException();
            }
        }
    }

    // We append the zeros that we skipped at the beginning
    if (littleEndian)
    {
        while (chsIndex < len)
        {
            chs[chsIndex] = chars[0];
            chsIndex++;
        }
    }
    else
    {
        while (chsIndex < len)
        {
            chs[len - chsIndex - 1] = chars[0];
            chsIndex++;
        }
    }

    return new string(chs);
}

public static byte[] FromBaseN(string str, string chars, bool littleEndian = true, int len = -1)
{
    if (str.Length == 0 || len == 0)
    {
        return new byte[0];
    }

    // This should be the maximum length of the byte[] array. It's 
    // the opposite of the one used in ToBaseN.
    // Note that it can be passed as a parameter
    if (len == -1)
    {
        len = (int)Math.Ceiling(str.Length * Math.Log(chars.Length, 2) / 8);
    }

    BigInteger bi = BigInteger.Zero;
    BigInteger length2 = chars.Length;
    BigInteger mult = BigInteger.One;

    for (int j = 0; j < str.Length; j++)
    {
        int ix = chars.IndexOf(littleEndian ? str[j] : str[str.Length - j - 1]);

        // We didn't find the character
        if (ix == -1)
        {
            throw new ArgumentOutOfRangeException();
        }

        bi += ix * mult;

        mult *= length2;
    }

    var bytes = bi.ToByteArray();

    int len2 = bytes.Length;

    // BigInteger adds a 0 byte for positive numbers that have the
    // last byte > 0x7F
    if (len2 >= 2 && bytes[len2 - 1] == 0)
    {
        len2--;
    }

    int len3 = Math.Min(len, len2);

    byte[] bytes2;

    if (littleEndian)
    {
        if (len == bytes.Length)
        {
            bytes2 = bytes;
        }
        else
        {
            bytes2 = new byte[len];
            Array.Copy(bytes, bytes2, len3);
        }
    }
    else
    {
        bytes2 = new byte[len];

        for (int i = 0; i < len3; i++)
        {
            bytes2[len - i - 1] = bytes[i];
        }
    }

    for (int i = len3; i < len2; i++)
    {
        if (bytes[i] != 0)
        {
            throw new OverflowException();
        }
    }

    return bytes2;
}

請注意,它們真的很慢! 真的很慢! (10分鍾2分鍾)。 為了加快它們的速度,您可能需要重寫division / mod操作,以便它們直接在緩沖區上工作,而不是每次都重新創建由BigInteger完成的便箋BigInteger 它仍然會很慢。 問題是編碼第一個字節所需的時間是O(n),其中n是字節數組的長度(這是因為所有數組都需要除以36)。 除非您想使用5個字節的塊並丟失一些位。 Base36的每個符號帶有大約5.169925001位。 因此,這些符號中的8個將攜帶41.35940001位。 非常接近40個字節。

請注意,這些方法可以在little-endian模式和big-endian模式下工作。 輸入和輸出的字節順序是相同的。 兩種方法都接受len參數。 您可以使用它來修剪多余的0 (零)。 請注意,如果您嘗試使輸出太小而無法包含輸入,則會拋出OverflowException

System.Text.Encoding enc = System.Text.Encoding.ASCII;
string myString = enc.GetString(myByteArray);

您可以使用您需要的編碼:

System.Text.ASCIIEncoding,
System.Text.UnicodeEncoding,
System.Text.UTF7Encoding,
System.Text.UTF8Encoding

要匹配請求[az][0-9]您可以使用它:

Byte[] bytes = new Byte[] { 200, 180, 34 };
string result = String.Join("a", bytes.Select(x => x.ToString()).ToArray());

您將使用char分隔符來字符串表示字節。 要轉換回來,您需要拆分,並使用與.Select()相同的方法將string[]轉換為byte[]

通常使用2的冪 - 這樣一個字符映射到固定數量的位。 例如,32位字母表將映射到5位。 在這種情況下唯一的挑戰是如何反序列化可變長度字符串。

對於36位,您可以將數據視為一個大數字,然后:

  • 除以36
  • 將余數添加為結果的字符
  • 重復直到除法結果為0

或許說起來容易做起來難。

你可以使用modulu。 此示例將您的字節數組編碼為[0-9] [az]的字符串。 如果你想改變它。

    public string byteToString(byte[] byteArr)
    {
        int i;
        char[] charArr = new char[byteArr.Length];
        for (i = 0; i < byteArr.Length; i++)
        {
            int byt = byteArr[i] % 36; // 36=num of availible charachters
            if (byt < 10)
            {
                charArr[i] = (char)(byt + 48); //if % result is a digit
            }
            else
            {
                charArr[i] = (char)(byt + 87); //if % result is a letter
            }
        }
        return new String(charArr);
    }

如果您不想丟失用於解碼的數據,可以使用以下示例:

    public string byteToString(byte[] byteArr)
    {
        int i;
        char[] charArr = new char[byteArr.Length*2];
        for (i = 0; i < byteArr.Length; i++)
        {
            charArr[2 * i] = (char)((int)byteArr[i] / 36+48);
            int byt = byteArr[i] % 36; // 36=num of availible charachters
            if (byt < 10)
            {
                charArr[2*i+1] = (char)(byt + 48); //if % result is a digit
            }
            else
            {
                charArr[2*i+1] = (char)(byt + 87); //if % result is a letter
            }
        }
        return new String(charArr);
    }

現在你有一個雙字符串,當奇數char是36的乘法,偶數char是殘差。 例如:200 = 36 * 5 + 20 =>“5k”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM