Java:将byte []转换为base36字符串 [英] Java: convert byte[] to base36 String

查看:127
本文介绍了Java:将byte []转换为base36字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点迷茫.对于项目,我需要使用基数36将哈希函数(SHA256)的输出(即字节数组)转换为String.

I'm a bit lost. For a project, I need to convert the output of a hash-function (SHA256) - which is a byte array - to a String using base 36.

所以最后,我要转换哈希的(十六进制字符串表示形式)

So In the end, I want to convert the (Hex-String representation of the) Hash, which is

43A718774C572BD8A25ADBEB1BFCD5C0256AE11CECF9F9C3F925D0E52BEAF89

到base36,因此上面的示例字符串为:

to base36, so the example String from above would be:

3SKVHQTXPXTEINB0AT1P0G45M4KI8U0HR8PGB96DVXSTDJKI1

对于向base36的实际转换,我在StackOverflow上找到了一些代码:

For the actual conversion to base36, I found some piece of code here on 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编码的String表示形式?

so it's not even close to what I want. I tried to find a solution now, but it seems I'm a bit lost here. How do I get the base36-encoded String representation of the Hash that I need?

推荐答案

尝试使用 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字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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