How to convert this MD5 encode PHP to java - java

I have simply code in PHP like that
$hash = md5("testtesttest", TRUE);
echo $hash.'<br>';
$hash = md5($hash . "test", TRUE);
echo $hash.'<br>';
With 2 line fisrt in java, it's working good with my code
public static void main(String[] args) {
// String str = new String(md5x16("test"));
byte[] input = md5x16("testtesttest");
String t = new String(input);
System.out.println(t);
}
public static byte[] md5x16(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
return md5Bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But in line 3 and 4 in PHP, I can't do the same in Java
If I parse to String and add a "test" to it, I will get another result with PHP

Iraklis should be right. md5() gives you a hex-encoded output string by default. You only get the unencoded bytes like in Java by passing in TRUE for the optional $raw_output argument.
the lengths range from 29 to 32
hexString.append( Integer.toHexString(0xFF & message[ i ] ) );
function makeBrokenMD5($s) {
$hash= md5($s, TRUE);
$bytes= preg_split('//', $hash, -1, PREG_SPLIT_NO_EMPTY);
$broken= '';
foreach ($bytes as $byte)
$broken.= dechex(ord($byte));
return $broken;
}`

Related

Convert MD5 - base64 From JAVA to PHP

I have a problem converting this Java code that generate md5-base64 to php.
I'd try more then 5 hours but without success.
This is the java code:
public static void main(String[] args) {
// TODO code application logic here
try {
String string = "customString";
String format = "20190101000000";
StringBuilder sb = new StringBuilder();
sb.append(format);
sb.append(string);
String sb2 = sb.toString();
byte[] bytes = sb2.getBytes();
byte[] bArr = new byte[16];
MessageDigest instance2 = MessageDigest.getInstance("MD5");
instance2.update(bytes, 0, bytes.length);
instance2.digest(bArr, 0, 16);
PrintStream printStream6 = System.out;
String a2 = Base64.getEncoder().encodeToString(bArr);
if (a2.length() >= 20) {
a2 = a2.substring(0, 19).trim();
}
StringBuilder sb8 = new StringBuilder();
sb8.append("MD5 16: ");
sb8.append(a2);
printStream6.println(sb8.toString());
} catch (Exception e) {
System.out.println(e);
}
}
And this is my php
<?php
$string = 'customString';
$format = '20190101000000';
$res = $format . $string;
$md5 = md5($res, true);
echo $md5;
echo '------------------';
$base = base64_encode($md5);
echo $base;
echo '------------------';
$result = substr($base, 0, 19);
echo $result;
echo '------------------';
The Java result is 1B2M2Y8AsgTpgAmY7Ph and php is iSKxA+7Y1mMnHhwf0yb
Check for charset encodings. In Java Strings are usually UTF-8 encoded. But when you transform to byte[] in sb2.getBytes(); it is using platform default charset (e.g. ISO-8859-1).
You have to provide the charset in java to have a determined behavior:
sb2.getBytes(java.nio.charset.Charset.forName("UTF-8");
or, the other way round, if goal isn't simply to make both reproduce same output, but you have to implement a PHP solution compatible with your existing Java solution, convert the PHP UTF-8 string to correct charset before md5(...). Therefore use iconv method.

Decode multiple times encoded String

I have written Java code to decode a string encoded with "UTF-8". That String was encoded three times. I am using this code in the ETL. so, I can use an ETL step three times in a row, but it will be a little inefficient. I researched over the internet but didn't find anything promising. Is there any way in Java to decode the String encoded multiple times?
Here's my input string "uri":
file:///C:/Users/nikhil.karkare/dev/pentaho/data/ba-repo-content-original/public/Development+Activity/Defects+Unresolved+%252528by+Non-Developer%252529.xanalyzer
Here's my code which is decoding this string:
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.io.*;
String decodedValue;
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
// First, get a row from the default input hop
//
Object[] r = getRow();
// If the row object is null, we are done processing.
//
if (r == null) {
setOutputDone();
return false;
}
// It is always safest to call createOutputRow() to ensure that your output row's Object[] is large
// enough to handle any new fields you are creating in this step.
//
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
String newFileName = get(Fields.In, "uri").getString(r);
try{
decodedValue = URLDecoder.decode(newFileName, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
// Set the value in the output field
//
get(Fields.Out, "decodedValue").setValue(outputRow, decodedValue);
// putRow will send the row on to the default output hop.
//
putRow(data.outputRowMeta, outputRow);
return true;}
Output of this code is following:
file:///C:/Users/nikhil.karkare/dev/pentaho/data/ba-repo-content-original/public/Development Activity/Defects Unresolved %2528by Non-Developer%2529.xanalyzer
When I run this code in the ETL three times, I get the output I want, which is this:
file:///C:/Users/nikhil.karkare/dev/pentaho/data/ba-repo-content-original/public/Development Activity/Defects Unresolved (by Non-Developer).xanalyzer
URL encoding replaces %, ( and ) with resp. %25.%28 and %29.
String s = "file:///C:/Users/nikhil.karkare/dev/pentaho/data/"
+ "ba-repo-content-original/public/Development+Activity/"
+ "Defects+Unresolved+%252528by+Non-Developer%252529.xanalyzer";
// %253528 ... %252529
s = URLDecoder.decode(s, "UTF-8");
// %2528 ... %2529
s = URLDecoder.decode(s, "UTF-8");
// %28 .. %29
s = URLDecoder.decode(s, "UTF-8");
// ( ... )
Just a for loop did the job:
String newFileName = get(Fields.In, "uri").getString(r);
decodedValue = newFileName;
for (int i=0; i<=3; i++){
try{
decodedValue = URLDecoder.decode(decodedValue, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new AssertionError("UTF-8 is unknown");
}
}

Translate HmacSHA1 checksum generating method from Java to PHP

I would like to translate the following Java method to PHP:
private byte[] generateChecksum(byte[] inData){
try{
byte[] b_key = secretValue.getBytes("ISO-8859-1");
SecretKeySpec sha1Key = new SecretKeySpec(b_key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sha1Key);
byte[] sigBytes = mac.doFinal(inData);
return sigBytes;
}catch(Exception e){
log.error("problem create hash: " + e);
return null;
}
}
I came up with the following, but it doesn't seem to be producing the same results as the Java method:
private function generateChecksum ( $inData ) {
try {
$hash = hash_hmac( 'sha1', $inData, $this->secretValue, TRUE );
return $this->getBytes( $hash );
} catch (Exception $e) {
return null;
}
}
I resolved it. The issue was caused by passing the $inData to hash_hmac( ) as a byte array instead of a string.

MD5 encoded parameter in URL

I am using following code to encrypt my email id in Java and sending it as a parameter in url (Using URLEncoder.encode(encrypteInput("email"))):
public static String encrypteInput(String input) {
String output = null;
input = input + ((int) Math.random()) % 1000;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
output = new String(md5.digest(input.getBytes()));
} catch (Exception e) {
output = "";
}
return output;
}
but, when I am getting the same parameter from servlet, it is not giving me the same output as encrypteInput("email").
Whenever you have a byte array that you want to store in a string, you should be Hex- or Base64-encoding the byte array (hex-encoding is probably better in this particular case).
Apache commons-codec has a Hex class you can use for this:
byte[] bytes = ...
char[] encoded = Hex.encodeHex(bytes);
String encodedString = new String(encoded);

Convert Byte String to alpha-numeric char array in java?

My question is, I guess, quite simple :
How to convert a Byte to alpha-numeric char array (String) in java ?
I tried this but it gives me back an error on netbeans :
byte[] b = "test".getBytes("ASCII");
String test = new String(b,"ASCII");
UPDATE :
I am actually using this code :
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
String bla = new String(md.digest(b), "ASCII");
But once I try to use for other stuff which requires String with ASCII, I receive the following errors like "This is not ASCII".
I don't really understand, actually.
When I try to print it I got something weird like "2Q�h/�k�����"
Thank you in advance for your help.
You're close :
public static void main(String[] args) throws java.io.UnsupportedEncodingException { //you should throw or catch this exception
byte[] b = "test".getBytes("ASCII"); // And you must declare a byte array
String test = new String(b,"ASCII");
System.out.println(test); // Will output "test"
}
After your edits I think you want to generate a SHA-256 hash of a given String.
try {
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(b);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & hashBytes[i]));
}
System.out.println(hexString);
} catch (Exception e) {
e.printStackTrace();
}

Categories