Is Crypto.generateMac method work exactly the same as Mac and SecretKeySpec java classes












1















I need to create a signature in order to send a request to CyberSource. I have the following Java code, that works perfectly:



String signatureString = "Test";

final Mac sha256HMAC = Mac.getInstance("HmacSHA256");
final SecretKeySpec secretKey = new SecretKeySpec(

Base64.getDecoder().decode("LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY="), "HmacSHA256");
sha256HMAC.init(secretKey);
sha256HMAC.update(signatureString.toString().getBytes(StandardCharsets.UTF_8));
final byte hashBytes = sha256HMAC.doFinal();
final String signatureB64 = Base64.getEncoder().encodeToString(hashBytes);
System.out.println(signatureB64.toString()); //nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=


I tried to make the same on Apex, but it shows me different result:



String signatureString = 'Test';
System.debug(generateHmacSHA256Signature(signatureString, 'LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY=')); //5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk=

public static String generateHmacSHA256Signature(String input, String secretKey) {
String algorithmName = 'HmacSHA256';
Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), Blob.valueOf(Secretkey));
String macUrl = EncodingUtil.base64Encode(mac);
return macUrl;
}


So Java returns nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0= and Apex 5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk= results are different.



How can I get the same result, as in Java? Any help very appriciated.










share|improve this question





























    1















    I need to create a signature in order to send a request to CyberSource. I have the following Java code, that works perfectly:



    String signatureString = "Test";

    final Mac sha256HMAC = Mac.getInstance("HmacSHA256");
    final SecretKeySpec secretKey = new SecretKeySpec(

    Base64.getDecoder().decode("LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY="), "HmacSHA256");
    sha256HMAC.init(secretKey);
    sha256HMAC.update(signatureString.toString().getBytes(StandardCharsets.UTF_8));
    final byte hashBytes = sha256HMAC.doFinal();
    final String signatureB64 = Base64.getEncoder().encodeToString(hashBytes);
    System.out.println(signatureB64.toString()); //nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=


    I tried to make the same on Apex, but it shows me different result:



    String signatureString = 'Test';
    System.debug(generateHmacSHA256Signature(signatureString, 'LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY=')); //5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk=

    public static String generateHmacSHA256Signature(String input, String secretKey) {
    String algorithmName = 'HmacSHA256';
    Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), Blob.valueOf(Secretkey));
    String macUrl = EncodingUtil.base64Encode(mac);
    return macUrl;
    }


    So Java returns nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0= and Apex 5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk= results are different.



    How can I get the same result, as in Java? Any help very appriciated.










    share|improve this question



























      1












      1








      1








      I need to create a signature in order to send a request to CyberSource. I have the following Java code, that works perfectly:



      String signatureString = "Test";

      final Mac sha256HMAC = Mac.getInstance("HmacSHA256");
      final SecretKeySpec secretKey = new SecretKeySpec(

      Base64.getDecoder().decode("LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY="), "HmacSHA256");
      sha256HMAC.init(secretKey);
      sha256HMAC.update(signatureString.toString().getBytes(StandardCharsets.UTF_8));
      final byte hashBytes = sha256HMAC.doFinal();
      final String signatureB64 = Base64.getEncoder().encodeToString(hashBytes);
      System.out.println(signatureB64.toString()); //nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=


      I tried to make the same on Apex, but it shows me different result:



      String signatureString = 'Test';
      System.debug(generateHmacSHA256Signature(signatureString, 'LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY=')); //5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk=

      public static String generateHmacSHA256Signature(String input, String secretKey) {
      String algorithmName = 'HmacSHA256';
      Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), Blob.valueOf(Secretkey));
      String macUrl = EncodingUtil.base64Encode(mac);
      return macUrl;
      }


      So Java returns nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0= and Apex 5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk= results are different.



      How can I get the same result, as in Java? Any help very appriciated.










      share|improve this question
















      I need to create a signature in order to send a request to CyberSource. I have the following Java code, that works perfectly:



      String signatureString = "Test";

      final Mac sha256HMAC = Mac.getInstance("HmacSHA256");
      final SecretKeySpec secretKey = new SecretKeySpec(

      Base64.getDecoder().decode("LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY="), "HmacSHA256");
      sha256HMAC.init(secretKey);
      sha256HMAC.update(signatureString.toString().getBytes(StandardCharsets.UTF_8));
      final byte hashBytes = sha256HMAC.doFinal();
      final String signatureB64 = Base64.getEncoder().encodeToString(hashBytes);
      System.out.println(signatureB64.toString()); //nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=


      I tried to make the same on Apex, but it shows me different result:



      String signatureString = 'Test';
      System.debug(generateHmacSHA256Signature(signatureString, 'LZjfTQi8uxEn5VFI3S4Ml+8UY4y3b2F0aP8c8WuiQtY=')); //5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk=

      public static String generateHmacSHA256Signature(String input, String secretKey) {
      String algorithmName = 'HmacSHA256';
      Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), Blob.valueOf(Secretkey));
      String macUrl = EncodingUtil.base64Encode(mac);
      return macUrl;
      }


      So Java returns nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0= and Apex 5zJnHFYz6HklMZ8vR4rf7UJfjrumiexZeYDgsuErrk= results are different.



      How can I get the same result, as in Java? Any help very appriciated.







      apex java crypto






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 19 at 14:38







      Oleksandr Berehovskyi

















      asked Mar 19 at 14:23









      Oleksandr BerehovskyiOleksandr Berehovskyi

      10.2k32239




      10.2k32239






















          1 Answer
          1






          active

          oldest

          votes


















          5














          Your Apex code just misses the base64 decoding step on your secret key. If you change the call to generateMac() to this:



          Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), EncodingUtil.base64Decode(Secretkey));


          You'll get back




          10:39:43:003 USER_DEBUG [2]|DEBUG|nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=







          share|improve this answer



















          • 1





            I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

            – Oleksandr Berehovskyi
            Mar 19 at 14:44













          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "459"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f254457%2fis-crypto-generatemac-method-work-exactly-the-same-as-mac-and-secretkeyspec-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          5














          Your Apex code just misses the base64 decoding step on your secret key. If you change the call to generateMac() to this:



          Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), EncodingUtil.base64Decode(Secretkey));


          You'll get back




          10:39:43:003 USER_DEBUG [2]|DEBUG|nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=







          share|improve this answer



















          • 1





            I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

            – Oleksandr Berehovskyi
            Mar 19 at 14:44


















          5














          Your Apex code just misses the base64 decoding step on your secret key. If you change the call to generateMac() to this:



          Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), EncodingUtil.base64Decode(Secretkey));


          You'll get back




          10:39:43:003 USER_DEBUG [2]|DEBUG|nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=







          share|improve this answer



















          • 1





            I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

            – Oleksandr Berehovskyi
            Mar 19 at 14:44
















          5












          5








          5







          Your Apex code just misses the base64 decoding step on your secret key. If you change the call to generateMac() to this:



          Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), EncodingUtil.base64Decode(Secretkey));


          You'll get back




          10:39:43:003 USER_DEBUG [2]|DEBUG|nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=







          share|improve this answer













          Your Apex code just misses the base64 decoding step on your secret key. If you change the call to generateMac() to this:



          Blob mac = Crypto.generateMac(algorithmName, Blob.valueOf(input), EncodingUtil.base64Decode(Secretkey));


          You'll get back




          10:39:43:003 USER_DEBUG [2]|DEBUG|nbXkkkM3GuPp8YEIb7JnAj4IrDy0YC7t3Pl/cJxStW0=








          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 19 at 14:40









          David ReedDavid Reed

          37.9k82256




          37.9k82256








          • 1





            I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

            – Oleksandr Berehovskyi
            Mar 19 at 14:44
















          • 1





            I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

            – Oleksandr Berehovskyi
            Mar 19 at 14:44










          1




          1





          I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

          – Oleksandr Berehovskyi
          Mar 19 at 14:44







          I wasted almost all day to try different combinations of EncodingUtil.base64Decode and Blob.valueOf, but on more complicated input... What's a fresh view mean!

          – Oleksandr Berehovskyi
          Mar 19 at 14:44




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Salesforce Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsalesforce.stackexchange.com%2fquestions%2f254457%2fis-crypto-generatemac-method-work-exactly-the-same-as-mac-and-secretkeyspec-java%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

          Alcedinidae

          Origin of the phrase “under your belt”?