Java create hash example


private void main(){
String hashKey  = createHash("str123")
}

public static String createHash(String str) {
    Cipher c;
    DESKeySpec dk;
    SecretKey secretKey;
    try {
      dk = new DESKeySpec(new Long(serialVersionUID).toString().getBytes());
      SecretKeyFactory kf;
      kf = SecretKeyFactory.getInstance("DES");
      secretKey = kf.generateSecret(dk);

      c = Cipher.getInstance("DES/ECB/PKCS5Padding");
      c.init(Cipher.ENCRYPT_MODE, secretKey);
      byte[] encrypted = c.doFinal(str.getBytes());

      // convert into hexadecimal number, and return as character string.
      String result = "";
      for (int i = 0; i < encrypted.length; i++) {
        result += byte2HexStr(encrypted[i]);
      }
      return result;

    } catch (InvalidKeyException e) {
      // log.error("The information of the private key may be broken.", e);
    } catch (IllegalBlockSizeException e) {
      // log.error("The length of data is unjust.", e);
    } catch (NoSuchAlgorithmException e) {
      // SecretKeyFactory
    } catch (InvalidKeySpecException e) {
      // generateSecret
    } catch (NoSuchPaddingException e) {
      // Cipher.getInstance
    } catch (BadPaddingException e) {
      // Cipher doFinal
    }
    return "";
  }

Comments

Popular Posts