Hash a password with SHA1 in java - java

I want to insert a password to my database using SHA1 hash
I do it manually in phpmyadmin by choosing the function sha1 but how to do this using Java ??
Any Idea ? Thank you!

If you must use java:
import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
public class SHACheckSumExample
{
public static void main(String[] args)throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
ByteArrayInputStream fis = new ByteArrayInputStream(args[1].getBytes());
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Hex format : " + sb.toString());
//convert the byte to hex format method 2
StringBuffer hexString = new StringBuffer();
for (int i=0;i<mdbytes.length;i++) {
hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
}
System.out.println("Hex format : " + hexString.toString());
}
}
I would, for performance reasons, suggest seeing if your database has SHA support. I know Postgres does, not sure about other systems.

Related

How to edit SHA256 in java

It was hard for me to explain in the title, but I would like to create a program which takes certain text, say hello0, hash it in sha256, and see if it has two leading zeros. If so, print hash. If not, make it hello1, then hello2 and so on until two leading zeros are found. Here is a few ways I found on how to create my sha256 hash from text:
import java.security.MessageDigest;
public class sha
{
public static void main(String[] args)throws Exception
{
int yeah = 40;
String password = "previousblock14currentblock" + yeah;
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(password.getBytes());
byte byteData[] = md.digest();
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Hex format : " + sb.toString());
StringBuffer hexString = new StringBuffer();
for (int i=0;i<byteData.length;i++) {
String hex=Integer.toHexString(0xff & byteData[i]);
if(hex.length()==1) hexString.append('0');
hexString.append(hex);
}
System.out.println("Hex format : " + hexString.toString());
}
}
When you run the code you receive Hex format : 0a0a30b1031fa60b8fa9478a070b03333df75017fd61c1b1c7e16bd929831ef5. This has one leading zero but I want two. I don't know what to do next, but i believe I set everything up correctly. How would I go about creating a while or if statement, each time adding yeah by 1? Would this be the best way of doing it?
The issue is that when I create a while loop the sha256 hash wont update, so it always prints 0a0a30b1031fa60b8fa9478a070b03333df75017fd61c1b1c7e16bd92983‌​1ef5. I'm wondering if I'm doing something wrong and wanted to see how someone else would do it.
thank you for your help.
public class Sha {
private static String byteArrayToHexString(byte[] array) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append(Integer.toString((array[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
final int MAX_PASS_ATTEMPTS = 40000;
final String PASS_PREFIX = "previousblock14currentblock";
MessageDigest md = MessageDigest.getInstance("SHA-256");
for (int i = 0; i < MAX_PASS_ATTEMPTS; i++) {
String password = PASS_PREFIX + i;
md.reset();
md.update(password.getBytes());
byte[] hash = md.digest();
//System.out.println(byteArrayToHexString(hash));
if (hash[0] == 0 && hash[1] == 0) {
System.out.println("Password: " + password);
System.out.println("Hash: " + byteArrayToHexString(hash));
return;
}
}
System.out.println("No luck after " + MAX_PASS_ATTEMPTS + " tries.");
}
}
By the way, this is the great resource to learn about Java control flow statements.

how can i find php md5(sha1("test")) in java

In my existing system, i have hashed the password with the following algorithm in php.
$userId = "testusername";
$password = "testpassword";
echo md5(sha1($userId).sha1($password));
what will be the equivalent method in Java for the above, because i was migrating php to java.
when i tried to search in google, they are talking about MessageDigest method.
In PHP i have used the inbuild md5() and sha1() function
in java, i found the following, but still, its not equivalent.
public static String sha1(String input) {
StringBuilder sb = null;
try{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(input.getBytes());
byte[] bytes = md.digest();
sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
}catch(RuntimeException | NoSuchAlgorithmException e){
throw new RuntimeException(e.getMessage());
}
return sb.toString();
}
public static String md5(String input) {
StringBuilder sb = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte[] bytes = md.digest();
sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
} catch (RuntimeException | NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
}
return sb.toString();
}
}
You can try bellow example :
class Main {
public static void main(String[] a) throws UnsupportedEncodingException, NoSuchAlgorithmException {
String output, input = "ml";
MessageDigest md = MessageDigest.getInstance("md5");
byte[] digest = md.digest(input.getBytes("UTF-8"));
BigInteger bigInt = new BigInteger(1, digest);
output = bigInt.toString(16);
System.out.println(""+output);
}
}
In the same way you also can generate sha1 just pass "sha1" in MessageDigest.getInstance(); function.
sha1($userId)+sha1($password) completely wrong. To do string concatenation in PHP you need sha1($userId).sha1($password)
The result you're seeing in PHP is actually md5(8) or c9f0f895fb98ab9159f51fd0297e236d. This is because the SHA1 of $password begins with an 8. The rest of the hash is thrown away.
This can not be used as a secure hashing function because there are too many collisions. For example, a password of 12345 has the same hash. You should require users to reset their passwords and use a standard password hashing mechanism instead.

Checksum doesn't match when computed string contains accented characters

First : I have a string which contains an accented character .
Second : I calcul the checksum for it .
private static String checkSumInStream(String Str, String checksumAlgorithm) throws Exception
{
InputStream stream = new ByteArrayInputStream(Str.getBytes());
MessageDigest digest = MessageDigest.getInstance(checksumAlgorithm);
InputStream input = null;
StringBuffer sb = new StringBuffer();
try{
input = stream;
byte[] buffer = new byte[8192];
do {
int read = input.read(buffer);
if(read <= 0)
break;
digest.update(buffer, 0, read);
} while(true);
byte[] sum = digest.digest();
for (int i = 0; i < sum.length; i++) {
sb.append(Integer.toString((sum[i] & 0xff) + 0x100, 16).substring(1));
}
}catch(IOException io)
{
}finally{
if(input != null)
input.close();
}
return sb.toString();
}
Then i write the string in text file and i I recalcul the checksum of the file
private String checkSum(File file,String checksumAlgorithm) throws Exception
{
MessageDigest digest = MessageDigest.getInstance(checksumAlgorithm);
InputStream input = null;
input = new FileInputStream(file);
byte[] buffer = new byte[8192];
do {
int read = input.read(buffer);
if(read <= 0)
break;
digest.update(buffer, 0, read);
} while(true);
input.close();
byte[] sum = digest.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < sum.length; i++) {
sb.append(Integer.toString((sum[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
--> Result : the comparison between checksum of an output steam and the file doesn't match when text contains an accented character .
How do you write the String to a file? You must be very careful to do that in the equivalent way of how you read it back from the file.
In your case:
OutputStream out = new FileOutputStream(myfile);
out.write(str.getBytes());
out.close();
Then it should work. But you need to keep in mind that str.getBytes() is not a safe method to use when you write to files, because it uses the platform default encoding for your characters. If you send such a file to some other place and use it there, you may be reading it back with the wrong encoding.
And it's possible that your platform default encoding doesn't even support accented characters! (But if you write and read files in exactly the same way, then you should get exactly the same result, so this wouldn't be the cause of your problem)
The best thing to do is to use the UTF-8 character encoding.
Where ever you used str.getBytes(), replace it with str.getBytes("UTF-8"), or str.getBytes(Charset.forName("UTF-8")) if you want to avoid having to catch UnsupportedEncodingException [even though every Java implementation is required to support the UTF-8 encoding. It's annoying...]

Android MD5 issue calculating MD5, missing characters

I've been developing an Android App and in certain part of the app I need to calculate the MD5 of a certain string. I've been using the following code, but every now and then the output string if the byte it has to convert to String is lower than 10, then it will miss a 0 in the two byte representation:
MessageDigest di = java.security.MessageDigest.getInstance("MD5");
di.update(cadena.getBytes());
byte mdi[] = di.digest();
StringBuffer md5= new StringBuffer();
for (byte b : mdi) {
md5.append(Integer.toHexString(0xFF & b));
}
For example, if I pass the string 109370 the MD5 it will have to return is 932ff0696b0434d7a83e1ff84fe298c5 but instead it calculates the 932ff0696b434d7a83e1ff84fe298c5.
That's because the byte array has a 4 and Integer.toHexString() is returning only 1 char array instead of two.
Any thought about how can I handle this?
Thanks!
below is the code that i am using:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Encode {
private static String convertedToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfOfByte = (data[i] >>> 4) & 0x0F;
int twoHalfBytes = 0;
do {
if ((0 <= halfOfByte) && (halfOfByte <= 9)) {
buf.append((char) ('0' + halfOfByte));
} else {
buf.append((char) ('a' + (halfOfByte - 10)));
}
halfOfByte = data[i] & 0x0F;
} while (twoHalfBytes++ < 1);
}
return buf.toString();
}
public static String MD5(String text) throws NoSuchAlgorithmException,
UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5 = md.digest();
return convertedToHex(md5);
}
}
and use it by this way:
MD5Encode.MD5("your string here")
hope this will help you :)
You can use a java.util.Formatter:
Formatter fmt = new Formatter(md5);
for (byte b : mdi) {
fmt.format("%02x", b&0xff);
}
fmt.close();
Use this:
public String calculateMD5(String string) {
StringBuilder result = new StringBuilder();
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(string.getBytes("UTF8"));
byte s[] = m.digest();
for (int i = 0; i < s.length; i++) {
result.append(Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6));
}
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Password hash is unsupported by device android implementation.", e);
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Password hash is unsupported by device android implementation.", e);
}
return result.toString();
}

How to calculate hash info for a torrent file in java?

I am building up a project based on p2p networking. And I am not able to find any algorithm to calculate hash info for a torrent file.
Can someone please help with the this?
You can use java.security.MessageDigest. Check the below program which calculates MD5Sum/hash bytes and converts it to Hex String format.
MessageDigest md5 = null;
byte[] buffer = new byte[1024];
int bytesRead = 0;
String md5ChkSumHex = null;
InputStream is = null;
String filePath = "D:/myFile.txt";
try
{
is = new FileInputStream(new File(filePath));
md5 = MessageDigest.getInstance("MD5");
try {
while ((bytesRead = is.read(buffer)) > 0) {
md5.update(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] md5ChkSumBytes = md5.digest();
StringBuffer sb = new StringBuffer();
/*Convert to hex*/
for (int j = 0; j < md5ChkSumBytes.length; j++)
{
String hex = Integer.toHexString(
(md5ChkSumBytes[j] & 0xff | 0x100)).substring(1, 3);
sb.append(hex);
}
md5ChkSumHex = sb.toString();
} catch (Exception nsae) {
}
return md5ChkSumHex;
There are many algorithms to find hash. Among them MD5 and SHA1 are popular algorithms.
In the above post, he mentioned the usage of MD5 Hasing. To do the SHA1 hasing, please use this post.

Categories