how can i find php md5(sha1("test")) in java - 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.

Related

Trouble understanding encryption code snippet

I am currently working on my final project for school. It´s a client management system, and on the login, I have decided to include an encryption feature so that clients can store their credentials without having to worry about their passwords being out in the open.
I have found this code online, and, since I'm still new on programming, I was wondering if you could give me a little bit of help regarding the meaning of the code.
I know what it does, I just need a little bit of explanation on how it does it.
Here is the code:
package Login;
import java.security.MessageDigest;
public class Encrypter {
public static void main(String[] args) {
String password = "password";
String algorithm = "SHA";
byte[] plainText = password.getBytes();
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithm);
} catch (Exception e) {
e.printStackTrace();
}
md.reset();
md.update(plainText);
byte[] encodedPassword = md.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encodedPassword.length; i++) {
if ((encodedPassword[i] & 0xff) < 0x10) {
sb.append("0");
}
sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
}
System.out.println("Plain : " + password);
System.out.println("Encrypted: " + sb.toString());
}
}

MD5 hash in android or java

I required to convert string in MD5 hash.
I am using
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex( byte[] bytes )
{
char[] hexChars = new char[ bytes.length * 2 ];
for( int j = 0; j < bytes.length; j++ )
{
int v = bytes[ j ] & 0xFF;
hexChars[ j * 2 ] = hexArray[ v >>> 4 ];
hexChars[ j * 2 + 1 ] = hexArray[ v & 0x0F ];
}
return new String( hexChars );
}
It is giving output like this website http://www.md5.cz/
but I required to generate hash as this http://webcodertools.com/hashstring giving output.
Please use test in both sites.
with using above function I am getting o/p like first site but I need as second site is giving.
Is there any different function or am I missing something in this?
Thanks.
The second web site is simply using base64 instead of hex to represent the binary data as text. So you can get rid of your bytesToHex method entirely, and just use Base64:
String base64Digest = Base64.encodeToString(thedigest, Base64.DEFAULT);
(As an aside, I'd avoid using the as a prefix in variable names - it provides no benefit, and is just cruft.)
Use this method it will return in the same format
public static String getMd5Hash(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getLocalizedMessage());
return null;
}
}
This returns in //4a2028eceac5e1f4d252ea13c71ecec6 format MD5 of "WHAT" and
String base64format = Base64.encodeToString(thedigest, Base64.DEFAULT); //as given by #Jon Skeet
will return in the format as SiAo7OrF4fTSUuoTxx7Oxg==
Sorry for vice-versa solution.

Java SHA512 digest output differs from PHP script

Can someone figure out why the output of these (php and java) snippets of code don't return the same SHA512 for the same input?
$password = 'whateverpassword';
$salt = 'ieerskzcjy20ec8wkgsk4cc8kuwgs8g';
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
echo "digest: ".base64_encode($digest);
for ($i = 1; $i < 5000; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
$encoded_pass = base64_encode($digest);
echo $encoded_pass;
This is the code on the android application:
public String processSHA512(String pw, String salt, int rounds)
{
try {
md = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("No Such Algorithm");
}
String result = hashPw(pw, salt, rounds);
System.out.println(result);
return result;
}
private static String hashPw(String pw, String salt, int rounds) {
byte[] bSalt;
byte[] bPw;
String appendedSalt = new StringBuilder().append('{').append(salt).append('}').toString();
try {
bSalt = appendedSalt.getBytes("ISO-8859-1");
bPw = pw.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported Encoding", e);
}
byte[] digest = run(bPw, bSalt);
Log.d(LCAT, "first hash: " + Base64.encodeBytes(digest));
for (int i = 1; i < rounds; i++) {
digest = run(digest, bSalt);
}
return Base64.encodeBytes(digest);
}
private static byte[] run(byte[] input, byte[] salt) {
md.update(input);
return md.digest(salt);
}
The library for base64 encoding is this: base64lib
This java code is actually some modified code I found around another question in StackOverflow.
Although the Android code is running fine it doesn't match with the output from the php script. It doesn't even match the first hash!
Note 1: On php hash('sha512',$input, $raw_output) returns raw binary output
Note 2: On java I tried to change the charset (UTF-8, ASCII) but it also didn't work.
Note 3: The code from the server can not be changed, so I would appreciate any answer regarding how to change my android code.
The first hash should be the same on the server and in Java. But then in the loop what gets appended to the digest is password{salt} in the PHP code, but only {salt} in the Java code.
For the lazy ones, one example better than a thousand words ;). I finally understood what was happening. The method update appends bytes to the digest, so when you append $password.{$salt} is the same as doing mda.update(password bytes) and the mda.digest("{$salt}" bytes. I do that answer because I was going crazy finding why it was not working and it was all in this answer.
Thanks guys.
This is the example that works in a Java Server:
public static String hashPassword(String password, String salt) throws Exception {
String result = password;
String appendedSalt = new StringBuilder().append('{').append(salt).append('}').toString();
String appendedSalt2 = new StringBuilder().append(password).append('{').append(salt).append('}').toString();
if(password != null) {
//Security.addProvider(new BouncyCastleProvider());
MessageDigest mda = MessageDigest.getInstance("SHA-512");
byte[] pwdBytes = password.getBytes("UTF-8");
byte[] saltBytes = appendedSalt.getBytes("UTF-8");
byte[] saltBytes2 = appendedSalt2.getBytes("UTF-8");
byte[] digesta = encode(mda, pwdBytes, saltBytes);
//result = new String(digesta);
System.out.println("first hash: " + new String(Base64.encode(digesta),"UTF-8"));
for (int i = 1; i < ROUNDS; i++) {
digesta = encode(mda, digesta, saltBytes2);
}
System.out.println("last hash: " + new String(Base64.encode(digesta),"UTF-8"));
result = new String(Base64.encode(digesta));
}
return result;
}
private static byte[] encode(MessageDigest mda, byte[] pwdBytes,
byte[] saltBytes) {
mda.update(pwdBytes);
byte [] digesta = mda.digest(saltBytes);
return digesta;
}

char[] -> String -> bytes[] -> String... and I'm lost

What I'm trying to do is to convert a password typed into a jPasswordField into SHA-256 hash. I was wandering around and found how to do this if I've got password saved as a string but the field I'm using is returning char[] so I ended up just guessing what to do... at first I've got different results even if the password was the same but now I believe I'm closer as it's a constant; but it's still not it as the output of
echo -n 'abc' | sha256sum
is
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
while the output of my action (for the same input) is
86900f25bd2ee285bc6c22800cfb8f2c3411e45c9f53b3ba5a8017af9d6b6b05
My action looks like this:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NoSuchAlgorithmException noSuchAlgorithmException = null;
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException ex) {
noSuchAlgorithmException = ex;
}
if (noSuchAlgorithmException != null) {
System.out.println(noSuchAlgorithmException.toString());
}
else {
UnsupportedEncodingException unsupportedEncodingException = null;
byte[] hash = null;
char[] password = jPasswordField1.getPassword();
StringBuffer stringBuffer = new StringBuffer();
for (char c : password) {
if (c > 0 && c < 16) {
stringBuffer.append("0");
}
stringBuffer.append(Integer.toHexString(c & 0xff));
}
String passwordString = stringBuffer.toString();
try {
hash = messageDigest.digest(passwordString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
unsupportedEncodingException = ex;
}
if (unsupportedEncodingException != null) {
System.out.println(unsupportedEncodingException.toString());
}
else {
stringBuffer = new StringBuffer();
for (byte b : hash) {
stringBuffer.append(String.format("%02x", b));
}
String passwordHashed = stringBuffer.toString();
System.out.println(passwordHashed);
}
}
Any ideas?
You've pretty much nailed it. just took the hard/wrong way converting from char[] to String -> new String(password) is all you need. (hint, if you find yourself manually converting between bytes and chars, you're probably doing it wrong).
as a side note, exceptions are "thrown" for a reason. that makes it easy to skip the following code which shouldn't be executed when the exception is thrown. by catching and turning the exceptions into "if" blocks, you make the code more complex than it needs to be.
This prints out the same hash as sha256sum
public static void main(String[] args)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
char[] password = new char[]{'a', 'b', 'c'};
MessageDigest messageDigest = null;
messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = null;
// This is how you convert a char array into a String without reencoding it into a different set of characters.
String passwordString = new String(password);
hash = messageDigest.digest(passwordString.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
String passwordHashed = sb.toString();
System.out.println(passwordHashed);
}

How to store password encrypted in database?

I am trying to store the password into the database in the encrypted form with the help of JSP and Servlets. How I can do that?
Self-written algorithms are a security risk, and painful to maintain.
MD5 is not secure.
Use the bcrypt algorithm, provided by jBcrypt (open source):
// Hash a password
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
// Check that an unencrypted password matches or not
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
If you use Maven, you can get the library by inserting the following dependency in your pom.xml (if a newer version is available please let me know):
<dependency>
<groupId>de.svenkubiak</groupId>
<artifactId>jBCrypt</artifactId>
<version>0.4.1</version>
</dependency>
Try something like this to encrypt your data.
MessageDigest md = MessageDigest.getInstance("MD5");
......
synchronized (md) {
md.reset();
byte[] hash = md.digest(plainTextPassword.getBytes("CP1252"));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < hash.length; ++i) {
sb.append(Integer.toHexString((hash[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
}
String password = sb.toString();
}
You can also use something like below. Below is a crypt method which takes a string input and will return and encrypted string. You can pass password to this method.
public static String crypt(String str) {
if (str == null || str.length() == 0) {
throw new IllegalArgumentException(
"String to encrypt cannot be null or zero length");
}
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes());
byte[] hash = md.digest();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0"
+ Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
} catch (NoSuchAlgorithmException e) {
}
return hexString.toString();
}

Categories