0

Hi i write below apex code for encryption SHA-512

   public class TestSimple {
    Public TestSimple(){  
    }
    public void decrytMethod(){
        String key = 'This is string';
        Blob digest = Crypto.generateDigest('SHA-512', Blob.valueOf(key));
        String s = EncodingUtil.base64Encode(digest);
        System.debug('Decrypt:'+s);
    }
}

It Give me output Decrypt: HUQXxm8VKM1ZMV/AnnZy40TX30IedtBUte4qsJuUb2IhyPJE8cLUvqExY+9gW7/f0z/M+M+YpZwTRBCB2Pt25Q==

I want some logic in java but in java its give me wrong response.. like

public String get_SHA_512_SecureString(String plainText){
    try{
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
    byte[] bytes = messageDigest.digest( plainText.getBytes() );
    StringBuilder sb = new StringBuilder();
    for(int i=0; i< bytes.length ;i++){
       sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
    }
     return sb.toString();

    }catch(Exception e){
        return "";
    }
}

In java its return 1d4417c66f1528cd59315fc09e7672e344d7df421e76d054b5ee2ab09b946f6221c8f244f1c2d4bea13163ef605bbfdfd33fccf8cf98a59c13441081d8fb76e5

I want java output is like apex output by passing same string side...?

3

Both languages are working fine. You are decoding them with wrong base.

Apex method is encoding blob as Base 64 and Java method is encoding it in Base 16. When you convert it in base 16 it output hex value of Blob. So, you should convert the value to hex by EncodingUtil.convertToHex as below.

public void decrytMethod()
{
        String key = 'This is string';
        Blob digest = Crypto.generateDigest('SHA-512', Blob.valueOf(key));
        String s = EncodingUtil.convertToHex(digest);
        System.debug('Decrypt:'+s);
        System.assertEquals(s,'1d4417c66f1528cd59315fc09e7672e344d7df421e76d054b5ee2ab09b946f6221c8f244f1c2d4bea13163ef605bbfdfd33fccf8cf98a59c13441081d8fb76e5');
}

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.