简体   繁体   中英

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM