comparison src/ch/ethz/ssh2/crypto/digest/MAC.java @ 273:91a31873c42a ganymed

start conversion from trilead to ganymed
author Carl Byington <carl@five-ten-sg.com>
date Fri, 18 Jul 2014 11:21:46 -0700
parents
children 071eccdff8ea
comparison
equal deleted inserted replaced
272:ce2f4e397703 273:91a31873c42a
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 if(type.equals("hmac-sha1-96")) {
36 return 20;
37 }
38 if(type.equals("hmac-md5")) {
39 return 16;
40 }
41 if(type.equals("hmac-md5-96")) {
42 return 16;
43 }
44 if(type.equals("hmac-sha2-256")) {
45 return 32;
46 }
47 if(type.equals("hmac-sha2-512")) {
48 return 64;
49 }
50 throw new IllegalArgumentException(String.format("Unknown algorithm %s", type));
51 }
52
53 public MAC(final String type, final byte[] key) throws DigestException {
54 if(type.equals("hmac-sha1")) {
55 mac = new HMAC(new SHA1(), key, 20);
56 }
57 else if(type.equals("hmac-sha1-96")) {
58 mac = new HMAC(new SHA1(), key, 12);
59 }
60 else if(type.equals("hmac-md5")) {
61 mac = new HMAC(new MD5(), key, 16);
62 }
63 else if(type.equals("hmac-md5-96")) {
64 mac = new HMAC(new MD5(), key, 12);
65 }
66 else if(type.equals("hmac-sha2-256")) {
67 mac = new HMAC(new SHA256(), key, 32);
68 }
69 else if(type.equals("hmac-sha2-512")) {
70 mac = new HMAC(new SHA512(), key, 64);
71 }
72 else {
73 throw new IllegalArgumentException(String.format("Unknown algorithm %s", type));
74 }
75 size = mac.getDigestLength();
76 }
77
78 public final void initMac(final int seq) {
79 mac.reset();
80 mac.update((byte) (seq >> 24));
81 mac.update((byte) (seq >> 16));
82 mac.update((byte) (seq >> 8));
83 mac.update((byte) (seq));
84 }
85
86 public final void update(byte[] packetdata, int off, int len) {
87 mac.update(packetdata, off, len);
88 }
89
90 public final void getMac(byte[] out, int off) throws IOException {
91 try {
92 mac.digest(out, off);
93 }
94 catch(DigestException e) {
95 throw new IOException(e);
96 }
97 }
98
99 public final int size() {
100 return size;
101 }
102 }