Java Key Pair Create generateKey(String seed)

Here you can find the source of generateKey(String seed)

Description

Create a DES key and return a string version of the raw bits.

License

Open Source License

Parameter

Parameter Description
seed a parameter

Exception

Parameter Description
NoSuchAlgorithmException an exception

Return

A key for encryption

Declaration

public static String generateKey(String seed) throws NoSuchAlgorithmException 

Method Source Code


//package com.java2s;

import java.security.*;

import javax.crypto.*;

public class Main {
    /**//w w w . jav a 2  s .  c o  m
     * Create a DES key and return a string version of the raw bits.
     *
     * @param seed
     * @return A key for encryption
     * @throws NoSuchAlgorithmException
     */
    public static String generateKey(String seed) throws NoSuchAlgorithmException {

        byte[] seedBytes = seed.getBytes();
        SecureRandom random = new SecureRandom(seedBytes);
        KeyGenerator keygen = null;
        try {
            keygen = KeyGenerator.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            throw e;
        }

        keygen.init(random);
        Key key = keygen.generateKey();

        byte[] keyBytes = key.getEncoded();

        return bytesToText(keyBytes);
    }

    /**
     * Convert bytes to text
     *
     * @param bytes
     * @return text for the input bytes
     */
    private static String bytesToText(byte[] bytes) {
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        for (int i = 0; i < bytes.length; i++) {
            int num = bytes[i];
            if (num < 0)
                num = 127 + (num * -1); // fix negative back to positive
            String hex = Integer.toHexString(num);
            if (hex.length() == 1) {
                hex = "0" + hex; // ensure 2 digits
            }
            sb.append(hex);
        }

        return sb.toString();
    }
}

Related

  1. generateKey(String keyPhrase)
  2. generateKey(String password)
  3. generateKey(String PRIVATE_KEY_FILE, String PUBLIC_KEY_FILE)
  4. generateKey(String publicKeyFilename, String privateKeyFilename, String password)
  5. generateKey(String secretKey)
  6. generateKey(String type)
  7. generateKey(String userKey, String masterKey)
  8. generateKeyAES()
  9. generateKeyDigest(int keyLength, String password)