How to generate a 48 character Hash using SHA384 in Java - java

i'm trying to generate a 48 character hash string in Java using SHA384, the output should look something like this:
PÊ&¿ a»#óæS0iÛ6në0Ê`o€X·„\KÃò¢ï¼fÖ…)nE#ó^s
My current implementation is as follows:
public static String getHash(byte[] inputBytes, String algorithm) throws Exception{
String hashValue = "";
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(inputBytes);
byte[] digestedBytes = messageDigest.digest();
hashValue =
DatatypeConverter.printHexBinary(digestedBytes).toLowerCase();
} catch(Exception e) {
e.printStackTrace();
}
return hashValue;
}
public static void main(String[] args) throws Exception {
System.out.println(getHash("The quick brown fox Jumps over the lazy dog".getBytes(), "SHA-384"));
}
Output:
b94a2179d90daf662f2ae8e41f92c2831eb0eea5a352f81ac7b0a80a07b2c357d88d0e3fc12bf4f0d888335508b09c41
As observed, the output string is a 96 Character string instead of 48, what am I doing wrong?

You can try something like this:
import java.security.MessageDigest;
public class Main {
public static String getHash(byte[] inputBytes, String algorithm) throws Exception{
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(inputBytes);
byte[] digestedBytes = messageDigest.digest();
return new String(digestedBytes, "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
System.out.println(getHash("The quick brown fox Jumps over the lazy dog".getBytes(), "SHA-384"));
}
}
This converts your 48 byte array into a String using the UTF-8 encoding. However, not all bytes represent printable characters, so you'll end up with a String with slightly fewer characters.

package com.journaldev.examples;
import java.util.UUID;
/**
* Java UUID randomUUID Example
*
*/
public class UUIDExample {
public static void main(String[] args) {
//initialize uuid
UUID uuid = UUID.randomUUID();
System.out.println(uuid);
}
}
Try this for generating random id's

Related

Hashing password by SHA256 then write to file

I try to Hash this password hoang1#H 3 times with 3 accounts by using SHA256. But when i write this password to file by using FileWriter and BufferedWriter, there are 3 different strings. Why ?
Here are my code for SHA256 hashing:
public byte[] getSHA(String input) throws NoSuchAlgorithmException
{
// Static getInstance method is called with hashing SHA
MessageDigest md = MessageDigest.getInstance("SHA-256");
// digest() method called
// to calculate message digest of an input
// and return array of byte
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public String toHexString(byte[] hash)
{
// Convert byte array into signum representation
BigInteger number = new BigInteger(1, hash);
// Convert message digest into hex value
StringBuilder hexString = new StringBuilder(number.toString(16));
// Pad with leading zeros
while (hexString.length() < 32)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
Code
You can test/run this code on ▶▶▶▶▶ https://replit.com/#JomaCorpFX/JavaHashes
HashAlgorithm.java
public enum HashAlgorithm {
SHA512("SHA-512"),
SHA256("SHA-256"),
SHA384("SHA-384"),
SHA1("SHA-1"),
MD5("MD5");
private String Value = "";
HashAlgorithm(String Value) {
this.Value = Value;
}
#Override
public String toString() {
return Value;
}
}
HexEncoder.java
import java.util.Formatter;
public class HexEncoder{
public static String toHex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length * 2);
try (Formatter formatter = new Formatter(sb))
{
for (byte b : data)
{
formatter.format("%02x", b);
}
}
return sb.toString();
}
}
HashManager.java
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public class HashManager {
public static byte[] toRawHash(byte[] data, HashAlgorithm algorithm) throws Exception
{
byte[] buffer = data;
MessageDigest messageDigest = MessageDigest.getInstance(algorithm.toString());
messageDigest.reset();
messageDigest.update(buffer);
return messageDigest.digest();
}
public static String toHexHash(byte[] data, HashAlgorithm algorithm) throws Exception
{
return HexEncoder.toHex(toRawHash(data, algorithm));
}
public static String toHexHash(String data, HashAlgorithm algorithm) throws Exception
{
return toHexHash(data.getBytes(StandardCharsets.UTF_8), algorithm);
}
}
Main.java
public class Main {
public static void main(String[] args) throws Exception {
String data = "grape";
System.out.println(HashManager.toHexHash(data, HashAlgorithm.SHA256));
System.out.println(HashManager.toHexHash(data, HashAlgorithm.SHA256));
System.out.println(HashManager.toHexHash(data, HashAlgorithm.SHA256));
System.out.println(HashManager.toHexHash(data, HashAlgorithm.SHA256));
}
}
Output
you should call md.reset() before reuse the MessageDigest instance.Just add it before md.digest(....).

Java error: void cannot be converted to String [duplicate]

This question already has an answer here:
What does "Incompatible types: void cannot be converted to ..." mean?
(1 answer)
Closed 3 years ago.
I know there are posts similar to this one, but I cannot seem to figure out my issue. I feel like it is something small, but my method does return a String, so I am no sure why it is telling me type void. I am new to java and would appreciate any help I can get. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;
public class Login{
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
String entered_username = Get_Credentials.get_username(user_input);
String entered_password = Get_Credentials.get_password(user_input);
String encrypted_password = MD5Digest.encrypt(entered_password);
user_input.close();
User[] all_users = File_Scanner.create_users();
}
}
class Get_Credentials{
public static String get_username(Scanner user_input){
System.out.println("Username: ");
return user_input.next();
}
public static String get_password(Scanner user_input){
System.out.println("Password: ");
return user_input.next();
}
}
class File_Scanner{
public static User[] create_users(){
User users[] = new User[6];
int index_counter = 0;
try {
File credentials_file = new File("credentials.txt");
String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
Scanner file_reader = new Scanner(credentials_file);
while (file_reader.hasNextLine()) {
users[index_counter] = new User();
users[index_counter].username = file_reader.findInLine(pattern);
users[index_counter].encrypted_password = file_reader.findInLine(pattern);
users[index_counter].password = file_reader.findInLine(pattern);
users[index_counter].role = file_reader.findInLine(pattern);
file_reader.nextLine();
index_counter++;
}
file_reader.close();
}
catch (Exception e) {
System.out.println(e.getClass());
}
return users;
}
}
class User {
String username;
String password;
String encrypted_password;
String role;
}
class MD5Digest {
public static void encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
}
}
Here is the error I am getting:
Login.java:15: error: incompatible types: void cannot be converted to String
encrypted_password = MD5Digest.encrypt(entered_password);
^
1 error
Your function has no return value void and you try to assign it to a string variable, that is what the error message means.
So change:
public static void encrypt(String original) throws Exception {
to
public static String encrypt(String original) throws Exception {
and
return sb.toString()
So the class looks like:
class MD5Digest {
public static String encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
return sb.toString();
}
}
BTW: Take care of Java's naming convention. Class names should be subjects.
EDIT:
Because your encrypt message throws an exception, you have to throw the exception also in public static void main(String []args) throws Exception{ or you have to handle it in a try-catch-block
In your code you are not returning anything for the method encrypt in MD5Digest class as below :
public static void encrypt(String original) throws Exception
That is the reason why compiler giving error as it is void type but the code is for String
Looks like you wanted to return a String, it should be as below :
class MD5Digest {
public static String encrypt(String original) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
System.out.println("original:" + original);
System.out.println("digested:" + sb.toString());
return sb.toString();
}
}

How to use Java encrypt Json by HmacSHA256

I have such a Json :
{
"idcardno":"510525198803154232",
"name":"丁品"
}
If I use HmacSHA256 encrypt it with key
252c04cdb0d047f8ab9a1eb49b1db1686e321104756ff792779a4d40d94f0dfd70a8b9ffa6d6d930e57d0e7206d26d13
Then I should get such result:
cd1fe72697a832d57198b8c0d00289309dffe6f05750aa2a145f9359e41f1843
I need to encrypt this json object in java environemnt, so I use below java code to achieve this:
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;
public class EncryptUtil {
// Charset to use when encrypting a string.
private static final String UTF_8 = "UTF-8";
// Encrypt key
private static final String APP_SECRET = "252c04cdb0d047f8ab9a1eb49b1db1686e321104756ff792779a4d40d94f0dfd70a8b9ffa6d6d930e57d0e7206d";
public static void main(String[] args) throws Exception {
//build json object
JSONObject object = new JSONObject();
object.put("idcardno", "510525198803154232");
object.put("name", "丁品");
String result = enCode(object.toString());
//print encrpted result
System.out.println(result);
}
public static String enCode(String orginalMsg) throws Exception {
try {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(APP_SECRET.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(orginalMsg.getBytes(UTF_8)));
return hash;
}
catch (Exception e){
throw new Exception(e);
}
}
}
But the encypted result is :
i2hF1WyxmS9MctkFLxBM2mgXeicraH9DhR9P9JySDFk=
How can get the correct result by Java code?

Why outputs in PHP and JAVA not equal

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Main {
public static void main(String[] args) {
String xmlRequest = " <request><merchant_id>46</merchant_id><order_id>33</order_id><amount>3</amount><description>hehe</description></request>";
String result = encode(xmlRequest);
String lol = "lol";
String lolResult = encode(lol);
System.out.println(result);
System.out.println(lolResult);
}
public static String encode(String toEncode) {
String hashStr = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(toEncode.getBytes());
BigInteger hash = new BigInteger(1, md.digest());
hashStr = hash.toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hashStr;
}
}
Output is:
aa4c157df0d6e95c395f2376fca94c7efa35c05d
403926033d001b5279df37cbbe5287b7c7c267fa
<?
$xml='<request><merchant_id>46</merchant_id><order_id>33</order_id><amount>3</amount><description>hehe</description></request>';
$x = sha1($xml);
echo $x;
echo sha1("lol");
?>
Output is:
d3cfa6c8ee0f7f12d28b782ac1eb45b777792e3a
403926033d001b5279df37cbbe5287b7c7c267fa
So, why string "lol" is equals and string of xml code is not?
You have an extra space - in the beginning of your java version in comparison to php, so it's not the same string

I have written the following program for XORing 2 cipher texts in hexadecimal using java. How do i convert output to ASCII

I have written the following program for XORing 2 cipher texts in hexadecimal using java. but the output is not correct. Also how do I convert the output in ASCII?
public class JavaApplication1 {
public static void main(String[] args) {
String y="a12104c6134e57914f104f2521ba4422c4d7b184f4815541f80484e1e24161d64d54ba2210194510164d4f3a0534304e43e1e1da524612171b11701be45431cc1d16a52d11744e1961a114de55174f84e54371";
String z="32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904";
String d;
String s="a";
char strfory[] = new char[2];
char strforz[] = new char[2];
String stry,strz;
for(int i=0; i<y.length();i+=2)
{
strfory[0]=y.charAt(i);
strfory[1]=y.charAt(i+1);
strforz[0]=z.charAt(i);
strforz[1]=z.charAt(i+1);
stry = new String(strfory);
strz = new String(strforz);
int a=Integer.parseInt(stry,16);
int b=Integer.parseInt(strz,16);
int c=a^b;
d=Integer.toHexString(c);
s=s.concat(d);
}
System.out.println(s);
}
}
Try to use java.math.BigInteger:
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.Arrays;
class Example {
private static final int VALUES_RADIX = 16;
private static final String FIRST_VALUE = "a12104c6134e57914f104f2521ba4422c4d7b184f4815541f80484e1e24161d64d54ba2210194510164d4f3a0534304e43e1e1da524612171b11701be45431cc1d16a52d11744e1961a114de55174f84e54371";
private static final String SECOND_VALUE = "32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904";
public static void main(String[] args) {
BigInteger firstValueToXor = new BigInteger(FIRST_VALUE, VALUES_RADIX);
BigInteger secondValueToXor = new BigInteger(SECOND_VALUE, VALUES_RADIX);
BigInteger result = firstValueToXor.xor(secondValueToXor);
String stringResultRepresentation = result.toString(VALUES_RADIX);
System.out.println(stringResultRepresentation);
try {
byte[] asciiResultRepresentation = stringResultRepresentation.getBytes("US-ASCII");
System.out.println(Arrays.toString(asciiResultRepresentation));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

Categories