XML Signatures - DigestValue

Soldato
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
I'm trying to understand something from W3C XML Signature page (https://www.w3.org/TR/xmldsig-core1/#sec-DigestValue), specifically about the DigestValue. It says.

A SHA-1 digest is a 160-bit string. The content of the DigestValue element shall be the base64 encoding of this bit string viewed as a 20-octet octet stream. For example, the DigestValue element for the message digest:

A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D

from Appendix A of the SHA-1 standard would be:

<DigestValue>qZk+NkcGgWq6PiVxeFDCbJzQ2J0=</DigestValue>

I'm probably being thick but how does that translate into that Base64? If I'm literal and run the octet bit string through a Base64 encoder I get something like

QTk5OTNFMzYgNDcwNjgxNkEgQkEzRTI1NzEgNzg1MEMyNkMgOUNEMEQ4OUQ=
 
Soldato
OP
Joined
1 Mar 2003
Posts
5,508
Location
Cotham, Bristol
Ok so I was being dumb, if anyone's interested always best to see with code. Essentially have to convert the hash from a hex string into a byte array first and then Base64 the byte array

Code:
public class Example {
    
    public static void main(String[] args) {
        String hash = "A9993E364706816ABA3E25717850C26C9CD0D89D";
        byte[] bytes = hexStringToByteArray(hash);
        System.out.println(Base64.getEncoder().encodeToString(bytes));
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
}

The above outputs qZk+NkcGgWq6PiVxeFDCbJzQ2J0=
 
Back
Top Bottom