function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Marley_06Marley_06 

Java method needs to be translated into Apex code for authentication in web service.

I have this sample java code below that I need to translate into apex code for authentication. I already used the EncodingUtil and Crypto class to generate the password but I failed to connect to the service. The nonce parameter is a random generated string and the timeCreatedStr is a timestamp.

public static String getPasswordDigest(String nonce, String timeCreatedStr, String password) 
            throws UnsupportedEncodingException {
        
        ByteBuffer buf = ByteBuffer.allocate(1000);
        buf.put(Base64.decodeBase64(nonce));
        buf.put(timeCreatedStr.getBytes("UTF-8"));
        buf.put(password.getBytes("UTF-8"));
        byte[] toHash = new byte[buf.position()];
        buf.rewind();
        buf.get(toHash);
        
        System.out.println("@@@buf "+buf);
        
        byte[] hashSha256 = DigestUtils.sha256(toHash);
        String passwordDigestSha256 = Base64.encodeBase64String(hashSha256);
        return passwordDigestSha256;
    }
May I ask if there is a way to translate the above code into apex? May I know what is the use of the ByteBuffer? Is there any Bytebuffer class in apex?

Thank you!
Best Answer chosen by Marley_06
Balaji Chowdary GarapatiBalaji Chowdary Garapati
@Marley_06 :

Try the below code:

return Encodingutil.base64Encode(Crypto.generateDigest('SHA-256',Blob.Value(nonce+timeCreatedStr+password)));

It returns a string which is the UTF-8 converted blob that was generated from DigestMethod using SHA-256 encoding technique.

Hope this will answer your question.

Thanks,
Balaji

All Answers

Balaji Chowdary GarapatiBalaji Chowdary Garapati
@Marley_06 :

Try the below code:

return Encodingutil.base64Encode(Crypto.generateDigest('SHA-256',Blob.Value(nonce+timeCreatedStr+password)));

It returns a string which is the UTF-8 converted blob that was generated from DigestMethod using SHA-256 encoding technique.

Hope this will answer your question.

Thanks,
Balaji
This was selected as the best answer
Balaji Chowdary GarapatiBalaji Chowdary Garapati
Hello George, Can you share your apex logic, so that i will try to see if i can help you and also the debug log if you can!! Thanks, Balaji
Marley_06Marley_06
Marley_06
Hi Balaji,

Apex logic:

public class testWebService {
    
    public testWebService() {
        someWS test = new someWS();
        test.TestService('mobile no.','message','companycode');
        
    }
    public string createNonce() {
       // return creates 26 random alpha-numeric characters
    }

    public string timeCreated() {
        // return timestamp
    }

    String staticPassword = "";

    public string passwordDigest(String nonce, String timeCreated, String staticPassword) {
        //returns Base64 ( SHA-256 ( nonce + created + password ) )
    }
    
    // SecurityHeaderType Class
    public class SecurityHeaderType 
    {       
        // Constructor for SecurityHeaderType used to pass in username and password parameters and instantiate the UsernameToken object     
        public SecurityHeaderType(String username, String password)
        {
            this.UsernameToken = new ARIS_POCSendSMSClass.UsernameToken(username, password);
        }

        public String wsuNamespace = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd';              
        public ARIS_POCSendSMSClass.UsernameToken UsernameToken;
        private String[] UsernameToken_type_info = new String[]{'UsernameToken','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','UsernameToken','1','1','false'};
        private String[] wsuNamespace_att_info = new String[]{'xmlns:wsu'};               
        private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
        private String[] field_order_type_info = new String[]{'UsernameToken'};
    }
}

In the web service class:

 public class someWS {
        public String endpoint_x = 'https://webservice';
        // ADDITION TO WSDL
        public testWebService.SecurityHeaderType Security = new testWebService.SecurityHeaderType( 'xxxx', 'xxxx');
        private String Security_hns = 'Security=http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd';                           
        // END ADDITION TO WSDL
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        //some code here...
}

 Note: I do not commit the error, when I put the generated passwords in java in apex. I really do not know what is causing this error:

System.CalloutException: Web service callout failed: Unexpected element. Parser was expecting element 'http://xxx:test1' but found 'http://xxx:test2'
usersfdc21usersfdc21
Hi Balaji,

I am trying Hmac algorithm to integrate SF to Third party.
I am getting 403 error: Forbiden request, invalid auth credential. May I know how to generate proper Hmac key. Thanks in advance.

blob blobSign = Crypto.generateDigest('SHA256', Blob.valueOf('privKey + data + unixTime'));
String HMACKey = EncodingUtil.convertToHex(blobSign);