2 * Copyright 2016 Huawei Technologies Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.openo.baseservice.encrypt.cbb.sha;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
21 import java.nio.charset.StandardCharsets;
22 import java.security.InvalidKeyException;
23 import java.security.Key;
24 import java.security.MessageDigest;
25 import java.security.NoSuchAlgorithmException;
27 import javax.crypto.Mac;
28 import javax.crypto.spec.SecretKeySpec;
29 import javax.xml.bind.DatatypeConverter;
32 * Utility to generate SHA256 digest and HMAC.<br/>
37 * @version 03-Jun-2016
39 public final class Sha256 {
41 private static final Logger LOGGER = LoggerFactory.getLogger(Sha256.class);
48 * Generates SHA256 digest.<br/>
50 * @param data: The data to be digested.
51 * @return Hex encoded digested data.
54 public static String digest(final String data) {
55 final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
56 MessageDigest md = null;
58 md = MessageDigest.getInstance("SHA-256");
59 } catch(final NoSuchAlgorithmException e) {
60 LOGGER.error("No SHA-256 support ", e);
63 final byte[] digest = md.digest(dataBytes);
64 return DatatypeConverter.printHexBinary(digest);
68 * Generates hmac signature using data and key.<br/>
70 * @param data: The data to be signed.
71 * @param key: The signing key.
72 * @return Hex encoded HMAC signature.
73 * @throws InvalidKeyException if the key is invalid.
76 public static String mac(final String data, final Key key) throws InvalidKeyException {
77 final byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
80 mac = Mac.getInstance("HmacSHA256");
82 } catch(final NoSuchAlgorithmException e) {
83 LOGGER.error("SHA mac not supported", e);
86 final byte[] digest = mac.doFinal(dataBytes);
87 return DatatypeConverter.printHexBinary(digest);
92 * Generates hmac with data and secret.
95 * @param data: The data to be signed.
96 * @param secret: The signing key.
97 * @return Hex encoded HMAC signature.
100 public static String mac(final String data, final byte[] secret) {
101 final Key key = new SecretKeySpec(secret, "HmacSHA256");
103 return mac(data, key);
104 } catch(final InvalidKeyException e) {
105 LOGGER.error("Invalid key: ", e);