amor amor - 11 months ago 261
PHP Question

Java equivalent for PHP pack() function

I have a PHP function. this code is to encryp a password

function md5_base64($txt)
return preg_replace('/=+$/','',base64_encode(pack('H*',md5($txt))));

Is any one know how can I write this in Java code.

this what I was try but dont give me result.

byte[] rawSHA = null;
byte[] base64HexSHA = null;
MessageDigest md= null;

try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
LOG.error("Unable to load MD5 Message Digest : " + e.getMessage(), e);
throw new IllegalStateException("MD5 Message Digest Instance Not Found");

rawSHA = md.digest(rawText.getBytes("UTF-8"));
base64HexSHA = Base64.encodeBase64(rawSHA);
System.out.println("result = "+base64HexSHA );

Thanks for help

I use this for base64 library

import org.apache.tomcat.util.codec.binary.Base64;

Answer Source

I have Solved this. this may help for other.

    String ps="tes";
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] encryptedPassword = md.digest(ps.getBytes());
    byte[] encodedBytes = Base64.encodeBase64(encryptedPassword);
    String Str2 = new String(encodedBytes);
    System.out.println("before =" + ps);
    System.out.println("after :" + Str2.replaceAll("[+$=]",""));

give me a result :

before =tes
after :KLZi2IO212/Zbk3cXpungA