how to base64 encode an unsigned byte array which is actually a int[]

1.8k views Asked by At

I have a problem to communicating between C# and JAVA. I have to hash a value in my program with SHA1 in JAVA. The problem is, computing hash in JAVA results a byte[] (so do C#, but:) byte type in JAVA is signed, while it's unsigned in C#. So I have to get rid of extra bits in JAVA (the C# side can not be touched). Here is what I'm doing:

private static int[] Hash(byte[] plainBytes, byte[] saltBytes)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    byte[] sourceBytes = new byte[plainBytes.length + saltBytes.length];
    for (int i = 0, il = plainBytes.length; i < il; i++)
        sourceBytes[i] = plainBytes[i];
    for (int i = 0, il = saltBytes.length, pil = plainBytes.length; i < il; i++)
        sourceBytes[pil + i] = saltBytes[i];
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    digest.reset();
    byte[] resultBytes = digest.digest(sourceBytes);
    int[] result = new int[resultBytes.length];
    for (int i = 0, il = resultBytes.length; i < il; i++)
        result[i] = ((int) resultBytes[i]) & 255;
    return result;
}

It gives me the correct array. But, the problem is base64 encoding the result. How can I do that without falling in signed byte trap again? I mean how to complete this snippet:

var resultArray = Hash(someSource, someSalt);
var resultBase64EncodedString = HOW_TO_BASE64_ENCODE_HERE(resultArray);

Thanks in advance.

1

There are 1 answers

0
josh On

Base64 encoding your resultBytes array with

String base64EncodedString = DatatypeConverter.printBase64Binary(resultBytes);

should give you the same base64 coded string as you get in C# with

SHA1 sha1 = SHA1.Create();
byte[] currentHash = new byte[0];
currentHash = sha1.ComputeHash(sourceBytes);
String base64EncodedString = Convert.ToBase64String(currentHash);