-
Notifications
You must be signed in to change notification settings - Fork 101
Closed
Description
Leaving the import import org.apache.commons.codec.binary.Base64
leads to a conflict with import java.util.Base64
and a compiler error
It also does not transform Base64.encodeBase64URLSafeString
From what I understand and tested, the closest to that is Base64.getUrlEncoder().withoutPadding().encodeToString
Sample class to reproduce this problem :
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class TokenGenerator {
private String generateSignature(final String appId, final String secret, final String version, final long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
final Mac mac = Mac.getInstance("HmacSHA256");
final byte[] hmacKeyBytes = Base64.decodeBase64(secret.getBytes());
final SecretKey secretKey = new SecretKeySpec(hmacKeyBytes, mac.getAlgorithm());
mac.init(secretKey);
final String input = appId + "-" + version + "-" + timestamp;
final byte[] rawHmac = mac.doFinal(input.getBytes());
return Base64.encodeBase64URLSafeString(rawHmac);
}
}
command I executed :
mvn rewrite:run -Drewrite.activeRecipes="org.openrewrite.java.migrate.apache.commons.codec.ApacheBase64ToJavaBase64"
diff :
@@ -16,6 +16,7 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
+import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@@ -111,7 +112,7 @@ public class TokenGenerator {
private String generateSignature(final String appId, final String secret, final String version, final long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
final Mac mac = Mac.getInstance("HmacSHA256");
- final byte[] hmacKeyBytes = Base64.decodeBase64(secret.getBytes());
+ final byte[] hmacKeyBytes = Base64.getDecoder().decode(secret.getBytes());
final SecretKey secretKey = new SecretKeySpec(hmacKeyBytes, mac.getAlgorithm());
mac.init(secretKey);
final String input = appId + "-" + version + "-" + timestamp;
Expected :
private String generateSignature(final String appId, final String secret, final String version, final long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
final Mac mac = Mac.getInstance("HmacSHA256");
final byte[] hmacKeyBytes = Base64.getDecoder().decode(secret.getBytes());
final SecretKey secretKey = new SecretKeySpec(hmacKeyBytes, mac.getAlgorithm());
mac.init(secretKey);
final String input = appId + "-" + version + "-" + timestamp;
final byte[] rawHmac = mac.doFinal(input.getBytes());
return Base64.getUrlEncoder().withoutPadding().encodeToString(rawHmac);
}
Metadata
Metadata
Assignees
Labels
bugSomething isn't workingSomething isn't working
Type
Projects
Status
Done