javabase64sha256http-authentication

Generating the same SHA-256 code_challenge as Postman using Java


When working on new HTTP request in Postman v11.2.14-canary01, and going to the Authorization tab and selecting SHA-256 for the Code Challenge Method and putting

6b890b254542c9de4603278153e1b127d21730d46ac2620e6e35514c

in the Code Verifier field, I can see that the https call says:

code_challenge=EKhdok_1ZKtBrevixgZqXxEHxn5pQjKkFA4bTVOmyH4

I'm trying to recreate this in Java.

        String text = "6b890b254542c9de4603278153e1b127d21730d46ac2620e6e35514c";
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        Base64.Encoder encoder = Base64.getEncoder();
        String value = encoder.encodeToString(hash);
        System.out.println("Result [" + value + "]");

Results in

Result [EKhdok/1ZKtBrevixgZqXxEHxn5pQjKkFA4bTVOmyH4=]

The results do not match. What are the specifics that should be used to "clean-up" the result?


Solution

  • It's using a Base64 URL encoding. Change

    Base64.Encoder encoder = Base64.getEncoder();
    

    to

    Base64.Encoder encoder = Base64.getUrlEncoder();
    

    With that one change, I get (as expected)

    Result [EKhdok_1ZKtBrevixgZqXxEHxn5pQjKkFA4bTVOmyH4=]
    

    The trailing = is padding.