View Javadoc
1   /*
2    * This file is part of Waarp Project (named also Waarp or GG).
3    *
4    *  Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5    *  tags. See the COPYRIGHT.txt in the distribution for a full listing of
6    * individual contributors.
7    *
8    *  All Waarp Project is free software: you can redistribute it and/or
9    * modify it under the terms of the GNU General Public License as published by
10   * the Free Software Foundation, either version 3 of the License, or (at your
11   * option) any later version.
12   *
13   * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14   * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15   * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16   *
17   *  You should have received a copy of the GNU General Public License along with
18   * Waarp . If not, see <http://www.gnu.org/licenses/>.
19   */
20  package org.waarp.common.crypto;
21  
22  import org.waarp.common.exception.CryptoException;
23  import org.waarp.common.logging.SysErrLogger;
24  
25  import javax.crypto.Cipher;
26  import javax.crypto.Mac;
27  import java.io.File;
28  import java.io.IOException;
29  
30  /**
31   * This class handles methods to crypt (not decrypt) messages with HmacSha256
32   * algorithm (very efficient:
33   * 105000/s).<br>
34   * <br>
35   * Usage:<br>
36   * <ul>
37   * <li>Create a HmacSha256 object: HmacSha256 key = new HmacSha256();</li>
38   * <li>Create a key:
39   * <ul>
40   * <li>Generate: key.generateKey();<br>
41   * The method key.getSecretKeyInBytes() allow getting the key in Bytes.</li>
42   * <li>From an external source: key.setSecretKey(arrayOfBytes);</li>
43   * </ul>
44   * </li>
45   * <li>To crypt a String in a Base64 format: String myStringCrypt =
46   * key.cryptToString(myString);</li>
47   * </ul>
48   */
49  public class HmacSha256 extends KeyObject {
50    private static final String ERROR = "Error: ";
51    private static final String CANNOT_BE_USED_FOR_HMAC_SHA256 =
52        "Cannot be used for HmacSha256";
53    private static final int KEY_SIZE = 128;
54    private static final String ALGO = "HmacSHA256";
55    private static final String INSTANCE = ALGO;
56    public static final String EXTENSION = "hs2";
57  
58    @Override
59    public final String getAlgorithm() {
60      return ALGO;
61    }
62  
63    @Override
64    public final String getInstance() {
65      return INSTANCE;
66    }
67  
68    @Override
69    public final int getKeySize() {
70      return KEY_SIZE;
71    }
72  
73    @Override
74    public final String getFileExtension() {
75      return EXTENSION;
76    }
77  
78    @Override
79    public final Cipher toCrypt() {
80      throw new IllegalArgumentException(CANNOT_BE_USED_FOR_HMAC_SHA256);
81    }
82  
83    @Override
84    public final byte[] crypt(final byte[] plaintext) throws Exception {
85      final Mac mac = Mac.getInstance(ALGO);
86      mac.init(secretKey);
87      return mac.doFinal(plaintext);
88    }
89  
90    @Override
91    public final Cipher toDecrypt() {
92      throw new IllegalArgumentException(CANNOT_BE_USED_FOR_HMAC_SHA256);
93    }
94  
95    @Override
96    public final byte[] decrypt(final byte[] ciphertext) throws Exception {
97      throw new IllegalArgumentException(CANNOT_BE_USED_FOR_HMAC_SHA256);
98    }
99  
100   /**
101    * Generates a HmacSha256 key and saves it into the file given as argument
102    *
103    * @param args
104    */
105   public static void main(final String[] args) {
106     if (args.length == 0) {
107       SysErrLogger.FAKE_LOGGER.syserr("Filename is needed as argument");
108     }
109     final HmacSha256 key = new HmacSha256();
110     try {
111       key.generateKey();
112     } catch (final Exception e) {
113       SysErrLogger.FAKE_LOGGER.syserr(ERROR + e.getMessage());
114       return;
115     }
116     try {
117       key.saveSecretKey(new File(args[0]));
118     } catch (final CryptoException e) {
119       SysErrLogger.FAKE_LOGGER.syserr(ERROR + e.getMessage());
120       return;
121     } catch (final IOException e) {
122       SysErrLogger.FAKE_LOGGER.syserr(ERROR + e.getMessage());
123       return;
124     }
125     SysErrLogger.FAKE_LOGGER.sysout(
126         "New HmacSha256 key file is generated: " + args[0]);
127   }
128 }