public static byte[] macWithSHA256(byte[] K, byte[] text, int macbytes) { MessageDigest sha256 = null; try { sha256 = SHA256.getMessageDigest(); HMAC_legacy hash = new HMAC_legacy(sha256); return hash.mac(K, text, macbytes); } finally { if(sha256 != null) SHA256.returnMessageDigest(sha256); } }
public static boolean verifyWithSHA256(byte[] K, byte[] text, byte[] mac) { MessageDigest sha256 = null; try { sha256 = SHA256.getMessageDigest(); HMAC_legacy hash = new HMAC_legacy(sha256); return hash.verify(K, text, mac); } finally { if(sha256 != null) SHA256.returnMessageDigest(sha256); } } }
public boolean verify(byte[] K, byte[] text, byte[] mac) { byte[] mac2 = mac(K, text, mac.length); // this is constant-time; DO NOT 'optimize' return MessageDigest.isEqual(mac, mac2); }
long t1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { byte[] r1 = HMAC_legacy.macWithSHA256(knownKey, plaintext, 32); for (int j = 0; j < r1.length; j++) { count += r1[j];
public static void main(String[] args) throws UnsupportedEncodingException { HMAC_legacy s = null; try { s = new HMAC_legacy(MessageDigest.getInstance("SHA1")); } catch(NoSuchAlgorithmException e) { throw new RuntimeException(e); key[i] = (byte) 0x0b; byte[] mv = s.mac(key, text, 20); System.out.println(HexUtil.bytesToHex(mv, 0, mv.length)); for(int i = 0; i < text.length; i++) text[i] = (byte) 0xdd; mv = s.mac(key, text, 20); System.out.println(HexUtil.bytesToHex(mv, 0, mv.length)); for(int i = 0; i < text.length; i++) text[i] = (byte) 0xcd; mv = s.mac(key, text, 20); System.out.println(HexUtil.bytesToHex(mv, 0, mv.length)); key[i] = (byte) 0x0c; text = "Test With Truncation".getBytes("UTF-8"); mv = s.mac(key, text, 20); System.out.println(HexUtil.bytesToHex(mv, 0, mv.length)); mv = s.mac(key, text, 12); System.out.println(HexUtil.bytesToHex(mv, 0, mv.length));