Java:将 byte[] 转换为 base36 字符串

标签 java converter base36

我有点迷路了。对于一个项目,我需要使用 base 36 将哈希函数 (SHA256) 的输出(它是一个字节数组)转换为字符串。

所以最后,我想转换哈希的(Hex-String 表示形式),即

43A718774C572BD8A25ADBEB1BFCD5C0256AE11CECF9F9C3F925D0E52BEAF89

到 base36,所以上面的示例字符串将是:

3SKVHQTXPXTEINB0AT1P0G45M4KI8U0HR8PGB96DVXSTDJKI1

对于实际转换为 base36,我在 StackOverflow 上找到了一段代码:

public static String toBase36(byte[] bytes) {
    //can provide a (byte[], offset, length) method too
    StringBuffer sb = new StringBuffer();
    int bitsUsed = 0; //will point how many bits from the int are to be encoded
    int temp = 0;
    int tempBits = 0;
    long swap;
    int position = 0;

    while((position < bytes.length) || (bitsUsed != 0)) {
        swap = 0;
        if(tempBits > 0) {
            //there are bits left over from previous iteration
            swap = temp;
            bitsUsed = tempBits;
            tempBits = 0;
        }
        //fill some bytes
        while((position < bytes.length) && (bitsUsed < 36)) {
            swap <<= 8;
            swap |= bytes[position++];
            bitsUsed += 8;
        }
        if(bitsUsed > 36) {
            tempBits = bitsUsed - 36; //this is always 4
            temp = (int)(swap & ((1 << tempBits) - 1)); //get low bits
            swap >>= tempBits; //remove low bits
            bitsUsed = 36;
        }
        sb.append(Long.toString(swap, 36));
        bitsUsed = 0;
    }
    return sb.toString();
}

现在我正在这样做:

// this creates my hash, being a 256-bit byte array
byte[] hash = PBKDF2.deriveKey(key.getBytes(), salt.getBytes(), 2, 256);

System.out.println(hash.length); // outputs "256"
System.out.println(toBase36(hash)); // outputs total crap

“完全废话”是这样的

-7-14-8-1q-5se81u0e-3-2v-24obre-73664-7-5-5cor1o9s-6h-4k6hr-5-4-rt2z0-30-8-2u-8-onz-4a2j-6-8-18-8trzza3-3-2x-6-4153to-4e3l01me-6-azz-2-k-4ckq-nav-gu-irqpxx-el-1j-6-rmf8hs-1bb5ax-3z25u-2-2r-t5-22-6-6w1v-1p

所以它甚至离我想要的还差得很远。我现在试图找到解决方案,但似乎我在这里有点迷路。如何获得我需要的哈希的 base36 编码字符串表示形式?

最佳答案

尝试使用 BigInteger:

String hash = "43A718774C572BD8A25ADBEB1BFCD5C0256AE11CECF9F9C3F925D0E52BEAF89";
//use a radix of 16, default would be 10 
String base36 = new BigInteger( hash, 16 ).toString( 36 ).toUpperCase();

关于Java:将 byte[] 转换为 base36 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915105/

相关文章:

xml - Ruby XML 到 JSON 转换器?

c# - 为什么这个 Base36 随机字符串不使用 RandomNumberGenerator 随机分布字符

sql - 仅使用 SQL 将 Base 36 转换为 Base 10

java 。关键字<这个>。迭代器模式

java - 是否需要参数

java - Jasper Reports - 限制组中的行数

java - 在Java中加载资源中不同文件夹下的属性

java - 需要改造 JSONAPI 转换器吗?

javascript - 将 ISO8601 日期转换为纪元格式(unix 时间戳)