-2

I am very new to Java and trying to use some Java code inside a custom sandbox environment that can support both java and javascript. It does not allow import or script statements though.

var sha256Hmac = javax.crypto.Mac.getInstance("HmacSHA256");
var secretKey = new javax.crypto.spec.SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256Hmac.init(secretKey);

When I print sha256Hmac, I get javax.crypto.Mac@7508cc45 and when I print secretKey, I get javax.crypto.spec.SecretKeySpec@fa75c355

I was able to use Hashmap and Base 64 like this and get the correct output

var hashMap = new java.util.HashMap();
hashMap.putAll(obj.getValues());
var payload = java.util.Base64.getUrlEncoder().encodeToString(hashMap.getBytes());
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    When you print an object in java it calls the objects `toString()` method and prints whatever that outputs exactly as you have shown `javax.crypto.Mac@7508cc45`, this is correct and default behaviour, the part before @ is the class, the part after @ is the hash code of the object. If you want different results then you need to retrieve the inner value from your object using a method call `obj.getValues()` or `String result = yourObject.someMetohd();` then print that, or you need to override the `toString()` method of the object, then you can just use `System.out.println(yourObject);`. – sorifiend Jul 27 '22 at 04:13

1 Answers1

0
var sha256Hmac = javax.crypto.Mac.getInstance("HmacSHA256");
var secretKey = new javax.crypto.spec.SecretKeySpec(secret.getBytes(java.nio.charset.StandardCharsets.UTF_8), "HmacSHA256");
sha256Hmac.init(secretKey);
var jwttoken = sha256Hmac.doFinal(data.getBytes(java.nio.charset.StandardCharsets.UTF_8));
var stoken = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(jwttoken);

The Base64 class by default returns a string so used it to convert the bytes[] to string.