Here you can find the source of generateKey(String seed)
Parameter | Description |
---|---|
seed | a parameter |
Parameter | Description |
---|---|
NoSuchAlgorithmException | an exception |
public static String generateKey(String seed) throws NoSuchAlgorithmException
//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(); } }