Skip to content

Commit

Permalink
[#3] Implements Base64URL encode / decode
Browse files Browse the repository at this point in the history
  • Loading branch information
raeperd committed May 14, 2021
1 parent 71c540d commit 2a4cffd
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package io.github.raeperd.realworld.infrastructure.jwt;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

class Base64URL {

private Base64URL() {
}

static String base64URLFromString(String rawString) {
return Base64.getUrlEncoder().withoutPadding()
.encodeToString(rawString.getBytes(StandardCharsets.UTF_8));
}

static String stringFromBase64URL(String base64URL) {
return new String(Base64.getUrlDecoder().decode(base64URL));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.github.raeperd.realworld.infrastructure.jwt;

import org.junit.jupiter.api.Test;

import java.util.Random;

import static io.github.raeperd.realworld.infrastructure.jwt.Base64URL.base64URLFromString;
import static io.github.raeperd.realworld.infrastructure.jwt.Base64URL.stringFromBase64URL;
import static org.assertj.core.api.Assertions.assertThat;

class Base64URLTest {

private final static String RAW_STRING = "something";
private final static String ENCODED_STRING = "c29tZXRoaW5n";

@Test
void when_encode_return_expected_string() {
assertThat(base64URLFromString(RAW_STRING)).isEqualTo(ENCODED_STRING);
}

@Test
void when_decode_return_expected_string() {
assertThat(stringFromBase64URL(ENCODED_STRING)).isEqualTo(RAW_STRING);
}

@Test
void when_encode_and_then_decode_expect_same() {
final var rawString = generateRandomString();

final var encodedString = base64URLFromString(rawString);
assertThat(stringFromBase64URL(encodedString)).isEqualTo(rawString);
}

private String generateRandomString() {
final var bytes = new byte[7];
new Random().nextBytes(bytes);
return new String(bytes);
}

}

0 comments on commit 2a4cffd

Please sign in to comment.