XSLT: Obtaining or matching hashes for base64 encoded data

大城市里の小女人 提交于 2019-11-30 05:50:28
Jukka Matilainen

For your related question about doing the base64 decoding in XSLT, you have accepted an answer which uses Saxon and Java extensions. So I assume you are OK with using those.

In that case, you can create an extension in Java for computing the MD5 sum:

package com.stackoverflow.q1684963;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Sum {
    public static String calc(byte[] data) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] digest = md5.digest(data);
        BigInteger digestValue = new BigInteger(1, digest);
        return String.format("%032x", digestValue);
    } 
}

From your XSLT 2.0 stylesheet which you run with Saxon, you can then just call that extension. Assuming you already have the base64-decoded data (for example from extension function saxon:base64Binary-to-octets as in the linked answer) in variable data:

<xsl:value-of xmlns:md5sum="com.stackoverflow.q1684963.MD5Sum"
              select="md5sum:calc($data)"/>
  • Download some freeware Base64 decoder like this one or use some source code from the web for this
  • Output file is some_file.gif, 268 bytes, a folder icon
  • Generate the MD5 checksum of that file using md5sum or again some source code from the web

Output for me:

4aaafc3e14314027bb1d89cf7d59a06c

That's what you wanted, isn't it? It will be tricky (if not impossible, and if you ask me, definitely not worth the effort) to do all this in XSLT, but at least you now have got the information that this hash was created using MD5 on the GIF file.

The 4aaaf... is the MD5 of the binary data you get when you decode the base64-encoded data. I don't think you have any choice but to decode the contents of <data> element and run it through an MD5 implementation, which is obviously outside the scope of an XSL transformation. Presumably, the result of the XSLT will be processed by some other code, which can extract and verify the images.

How about this (add commons-codec to your classpath):

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:digest="org.apache.commons.codec.digest.DigestUtils">
  [...]
  <xsl:value-of select="digest:md5Hex('hello, world!')"/>
</xsl:stylesheet>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!