This is my function that decodes a JWT Object to String:
protected String decodeJWT(String idToken){ String[] splitString = idToken.split("\."); String base64EncodedBody = splitString[1]; Base64 base64Url = new Base64(true); String idTokenString = new String(base64Url.decode(base64EncodedBody)); StringBuilder sub = new StringBuilder(); int indexStart = idTokenString.indexOf(""sub":"") + 7; char c; while((c = idTokenString.charAt(indexStart)) != '"') { indexStart++; sub.append(c); } return sub.toString(); }
SonarCloud detect a code smell when I convert base64Url.decode(base64EncodedBody)
, that is a byte[]
, on a String
.
This is the issue:
Constructors should not be used to instantiate “String”, “BigInteger”, “BigDecimal” and primitive-wrapper classes.
Constructors for String, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.
How can I resolve this code smell?
Advertisement
Answer
use this constructor
String(byte bytes[], Charset charset)
constructor instead
hence code can be changed as
String s = new String(base64Url.decode(base64EncodedBody), StandardCharsets.UTF_8);
refer https://gazelle.ihe.net/sonar/coding_rules?open=squid%3AS1943&rule_key=squid%3AS1943
String constructors with a byte[] argument but no Charset argument is a minor code smell