1/*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5package ch.ethz.ssh2.crypto.digest;
6
7/**
8 * MAC.
9 *
10 * @author Christian Plattner
11 * @version 2.50, 03/15/10
12 */
13public final class MAC
14{
15	Digest mac;
16	int size;
17
18	public static String[] getMacList()
19	{
20		/* Higher Priority First */
21
22		return new String[]{"hmac-sha1-96", "hmac-sha1", "hmac-md5-96", "hmac-md5"};
23	}
24
25	public static void checkMacList(String[] macs)
26	{
27		for (int i = 0; i < macs.length; i++)
28			getKeyLen(macs[i]);
29	}
30
31	public static int getKeyLen(String type)
32	{
33		if (type.equals("hmac-sha1"))
34			return 20;
35		if (type.equals("hmac-sha1-96"))
36			return 20;
37		if (type.equals("hmac-md5"))
38			return 16;
39		if (type.equals("hmac-md5-96"))
40			return 16;
41		throw new IllegalArgumentException("Unkown algorithm " + type);
42	}
43
44	public MAC(String type, byte[] key)
45	{
46		if (type.equals("hmac-sha1"))
47		{
48			mac = new HMAC(new SHA1(), key, 20);
49		}
50		else if (type.equals("hmac-sha1-96"))
51		{
52			mac = new HMAC(new SHA1(), key, 12);
53		}
54		else if (type.equals("hmac-md5"))
55		{
56			mac = new HMAC(new MD5(), key, 16);
57		}
58		else if (type.equals("hmac-md5-96"))
59		{
60			mac = new HMAC(new MD5(), key, 12);
61		}
62		else
63			throw new IllegalArgumentException("Unkown algorithm " + type);
64
65		size = mac.getDigestLength();
66	}
67
68	public void initMac(int seq)
69	{
70		mac.reset();
71		mac.update((byte) (seq >> 24));
72		mac.update((byte) (seq >> 16));
73		mac.update((byte) (seq >> 8));
74		mac.update((byte) (seq));
75	}
76
77	public void update(byte[] packetdata, int off, int len)
78	{
79		mac.update(packetdata, off, len);
80	}
81
82	public void getMac(byte[] out, int off)
83	{
84		mac.digest(out, off);
85	}
86
87	public int size()
88	{
89		return size;
90	}
91}
92