Skip to content

Instantly share code, notes, and snippets.

@julianjupiter
Last active June 20, 2024 11:24
Show Gist options
  • Save julianjupiter/a67fc7ad576c1beb8b429b16df121be6 to your computer and use it in GitHub Desktop.
Save julianjupiter/a67fc7ad576c1beb8b429b16df121be6 to your computer and use it in GitHub Desktop.
Create code verifier and code challenge for OIDC Authorization Code Flow with PKCE in Java
package com.julianjupiter.oidc;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/**
* @author Julian Jupiter
*/
public class OidcAuthCodeFlowWithPkce {
public static String createCodeVerifier() {
var secureRandom = new SecureRandom();
var code = new byte[32];
secureRandom.nextBytes(code);
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(code);
}
public static String createCodeChallenge(String verifier) throws NoSuchAlgorithmException {
byte[] bytes = verifier.getBytes(StandardCharsets.US_ASCII);
var messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(bytes, 0, bytes.length);
byte[] digest = messageDigest.digest();
return Base64.getUrlEncoder()
.withoutPadding()
.encodeToString(digest);
}
}
package com.julianjupiter.java.v21;
import java.security.NoSuchAlgorithmException;
import static com.julianjupiter.oidc.OidcAuthCodeFlowWithPkce.*;
/**
* @author Julian Jupiter
*/
public class Sample {
public static void main(String[] args) throws NoSuchAlgorithmException {
String codeVerifier = createCodeVerifier();
String codeChallenge = createCodeChallenge(codeVerifier);
System.out.printf("Code verifier: %s%n", codeVerifier);
System.out.printf("Code challenge: %s%n", codeChallenge);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment