comparison src/ch/ethz/ssh2/crypto/digest/MAC.java @ 342:175c7d68f3c4

merge ganymed into mainline
author Carl Byington <carl@five-ten-sg.com>
date Thu, 31 Jul 2014 16:33:38 -0700
parents 071eccdff8ea
children 8c1451f51a5e
comparison
equal deleted inserted replaced
272:ce2f4e397703 342:175c7d68f3c4
1 /*
2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved.
3 * Please refer to the LICENSE.txt for licensing details.
4 */
5 package ch.ethz.ssh2.crypto.digest;
6
7 import java.io.IOException;
8 import java.security.DigestException;
9
10 /**
11 * MAC.
12 *
13 * @author Christian Plattner
14 * @version 2.50, 03/15/10
15 */
16 public final class MAC {
17 private Digest mac;
18 private int size;
19
20 public static String[] getMacList() {
21 // Higher priority first. Added SHA-2 algorithms as in RFC 6668
22 return new String[] {"hmac-sha1-96", "hmac-sha1", "hmac-md5-96", "hmac-md5", "hmac-sha2-256", "hmac-sha2-512"};
23 }
24
25 public static void checkMacList(final String[] macs) {
26 for (String m : macs) {
27 getKeyLen(m);
28 }
29 }
30
31 public static int getKeyLen(final String type) {
32 if (type.equals("hmac-sha1")) {
33 return 20;
34 }
35
36 if (type.equals("hmac-sha1-96")) {
37 return 20;
38 }
39
40 if (type.equals("hmac-md5")) {
41 return 16;
42 }
43
44 if (type.equals("hmac-md5-96")) {
45 return 16;
46 }
47
48 if (type.equals("hmac-sha2-256")) {
49 return 32;
50 }
51
52 if (type.equals("hmac-sha2-512")) {
53 return 64;
54 }
55
56 throw new IllegalArgumentException(String.format("Unknown algorithm %s", type));
57 }
58
59 public MAC(final String type, final byte[] key) throws DigestException {
60 if (type.equals("hmac-sha1")) {
61 mac = new HMAC(new SHA1(), key, 20);
62 }
63 else if (type.equals("hmac-sha1-96")) {
64 mac = new HMAC(new SHA1(), key, 12);
65 }
66 else if (type.equals("hmac-md5")) {
67 mac = new HMAC(new MD5(), key, 16);
68 }
69 else if (type.equals("hmac-md5-96")) {
70 mac = new HMAC(new MD5(), key, 12);
71 }
72 else if (type.equals("hmac-sha2-256")) {
73 mac = new HMAC(new SHA256(), key, 32);
74 }
75 else if (type.equals("hmac-sha2-512")) {
76 mac = new HMAC(new SHA512(), key, 64);
77 }
78 else {
79 throw new IllegalArgumentException(String.format("Unknown algorithm %s", type));
80 }
81
82 size = mac.getDigestLength();
83 }
84
85 public final void initMac(final int seq) {
86 mac.reset();
87 mac.update((byte)(seq >> 24));
88 mac.update((byte)(seq >> 16));
89 mac.update((byte)(seq >> 8));
90 mac.update((byte)(seq));
91 }
92
93 public final void update(byte[] packetdata, int off, int len) {
94 mac.update(packetdata, off, len);
95 }
96
97 public final void getMac(byte[] out, int off) throws IOException {
98 try {
99 mac.digest(out, off);
100 }
101 catch (DigestException e) {
102 throw new IOException(e);
103 }
104 }
105
106 public final int size() {
107 return size;
108 }
109 }