Generates a random secret key. - Java Security

Java examples for Security:Key

Description

Generates a random secret key.

Demo Code

/*/* w w w.j  av a  2  s  . c om*/
 * Copyright (C) 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class Main {
    public static final String HMAC_SHA256 = "HmacSHA256";

    /**
     * Generates a random secret key.
     *
     * @return a random secret key.
     */
    public static String generateSecretKey() {
        return hmacDigest(UUID.randomUUID().toString(), UUID.randomUUID()
                .toString(), HMAC_SHA256);
    }

    public static String hmacDigest(String message, String secretKey,
            String algorithm) {
        String digest = null;
        try {
            SecretKeySpec key = new SecretKeySpec(
                    secretKey.getBytes(StandardCharsets.UTF_8), algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(key);

            byte[] bytes = mac.doFinal(message
                    .getBytes(StandardCharsets.US_ASCII));

            digest = toHex(bytes);
        } catch (InvalidKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        }
        return digest;
    }

    public static String toHex(byte[] bytes) {
        StringBuilder hash = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }
}

Related Tutorials