/** * Creates a message authentication code (MAC) for the given input. * * @param msg input * @param k secret key * @param a encryption algorithm * @param enc encoding * @return MAC * @throws QueryException query exception */ Item hmac(final byte[] msg, final byte[] k, final byte[] a, final byte[] enc) throws QueryException { // create hash value from input message final Key key = new SecretKeySpec(k, string(a)); final byte[] aa = a.length == 0 ? DEFA : a; if (!ALGHMAC.contains(lc(aa))) throw CX_INVHASH.get(info, aa); final boolean b64 = eq(lc(enc), BASE64) || enc.length == 0; if (!b64 && !eq(lc(enc), HEX)) throw CX_ENC.get(info, enc); try { final Mac mac = Mac.getInstance(string(ALGHMAC.get(lc(aa)))); mac.init(key); final byte[] hash = mac.doFinal(msg); // convert to specified encoding, base64 as a standard, else use hex return Str.get(b64 ? org.basex.util.Base64.encode(hash) : hex(hash, true)); } catch (final NoSuchAlgorithmException e) { throw CX_INVHASH.get(info, e); } catch (final InvalidKeyException e) { throw CX_KEYINV.get(info, e); } }
@Override public String toString() { return Util.info("\"%\"", org.basex.util.Base64.encode(data)); }
@Override public byte[] string(final InputInfo ii) throws QueryException { return org.basex.util.Base64.encode(binary(ii)); }