3

To summarize my problem, I want to adapt an encryption algorithm written in Javascript to the Java side. The content produced here is used in the header of the service I am calling. But even though I have tried many ways, I have not been able to find the real algorithm yet.

The algorithm written in Javascript is as follows:

function doFunction() {
    apiSecret = "ZDhhODhlOTI2ZjFmNGQ5MDlhMzg5Y2JhZTQyOGUzNDY=";
    date = (new Date()).toUTCString();
    signatureContentString = 'date: ' + date;
    signatureString = CryptoJS.HmacSHA1(signatureContentString, apiSecret).toString(CryptoJS.enc.Base64);
    authHeader = encodeURIComponent(signatureString);
    alert(authHeader);
}

The algorithm I tried on the Java side is as follows:

public String createCredential(){
    Date currentDate = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.RFC1123_PATTERN);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String date = simpleDateFormat.format(currentDate);
    String signatureContentString = "date: "+date;
    byte[] bytes = HmacUtils.hmacSha1(Constants.apiSecret, signatureContentString);
    byte[] encode = Base64.getEncoder().encode(bytes);
    String encoded = URLEncoder.encode(encode.toString(), StandardCharsets.UTF_8);
    return  encoded;
}

Example output when I try it on the javascript side:

rJxRUgl1%2Bxj5UZSC9rZAHxSl7fw%3D

Example output when I try it on the Java side:

%5BB%4079c7ad7f

The formats do not match each other. By the way, if you need the RFC1123_PATTERN constant;

public static final String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";

1 Answer 1

4

encode.toString() returns a String representing the byte[], s. e.g. here, but not, as you probably assume, an ASCII or UTF8 decoding.

For the latter use in the Java code:

byte[] encode = Base64.getEncoder().encode(bytes);
String encoded = URLEncoder.encode(new String(encode, StandardCharsets.UTF_8), StandardCharsets.UTF_8);

or alternatively:

String encode = Base64.getEncoder().encodeToString(bytes);
String encoded = URLEncoder.encode(encode, StandardCharsets.UTF_8);

Test:
For the date string Sat, 18 Jun 2022 17:07:55 GMT both codes return the value rSQNB1HOmHEPH982kd9ix0%2F%2F58A%3D.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried it now and it works flawlessly, thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.