List of usage examples for org.bouncycastle.util.encoders Encoder encode
int encode(byte[] data, int off, int length, OutputStream out) throws IOException;
From source file:com.nokia.xfolite.xforms.xpath.XFormsCoreFunctionLibrary.java
License:Open Source License
public static String digest_function(String s, String method, String encoding) { //#debug info System.out.println("Digest function invoked with params(" + s + "," + method + "," + encoding + ")"); Digest digest = null;/*from w ww .ja va2 s . com*/ Encoder encoder = null; if (encoding.equals("base64")) { encoder = new Base64Encoder(); } else if (encoding.equals("hex")) { encoder = new HexEncoder(); } if (method.equals("SHA-1")) { digest = new SHA1Digest(); } else if (method.equals("SHA-256")) { digest = new SHA256Digest(); } else if (method.equals("SHA-512")) { digest = new SHA512Digest(); } else if (method.equals("MD5")) { digest = new MD5Digest(); } if (encoder == null) { throw new XPathException(XPathException.TYPE_ERR, "XForms function digest() only supports hex and base64 encoding."); } if (digest == null) { throw new XPathException(XPathException.TYPE_ERR, "XForms function digest() only supports MD5, SHA-1, SHA-256 and SHA-512 digests."); } int len = s.length(); for (int i = 0; i < len; i++) { digest.update((byte) s.charAt(i)); // FIXME: Better not use non-ASCII characters! } byte[] data = new byte[digest.getDigestSize()]; digest.doFinal(data, 0); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, 0, data.length, bOut); } catch (IOException e) { throw new XPathException(XPathException.TYPE_ERR, "Exception when encoding digest: " + e); } byte[] out = bOut.toByteArray(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < out.length; i++) { sb.append((char) out[i]); // This works fine, neither hex nor base64 encodings produce } return sb.toString(); }