Add PKCEUtils.java

pull/4/head
shengzhaoli.shengz 1 year ago
parent c79b026f50
commit be545e3953

@ -0,0 +1,56 @@
package com.monkeyk.sos.infrastructure;
import org.apache.commons.lang3.RandomStringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* 2023/10/16 22:45
* <p>
* PKCE tool:
*
* @author Shengzhao Li
* @since 3.0.0
*/
public abstract class PKCEUtils {
private static final String ALG = "SHA-256";
private PKCEUtils() {
}
/**
* 32 code_verifier
*
* @return code_verifier
*/
public static String generateCodeVerifier() {
// 1. 随机生成code_verifier
String codeVerifierVal = RandomStringUtils.random(32, true, true);
//2. 对 code_verifier 进行base64 encode
return Base64.getEncoder().encodeToString(codeVerifierVal.getBytes(StandardCharsets.UTF_8));
}
/**
* code_verifier code_challenge
*
* @param codeVerifier code_verifier
* @return code_challenge
*/
public static String generateCodeChallenge(String codeVerifier) {
MessageDigest md;
try {
md = MessageDigest.getInstance(ALG);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("JDK not found alg: '" + ALG + "' ??", e);
}
byte[] digest = md.digest(codeVerifier.getBytes(StandardCharsets.US_ASCII));
return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
}
}

@ -0,0 +1,65 @@
package com.monkeyk.sos.infrastructure;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import static org.junit.jupiter.api.Assertions.*;
/**
* 2023/10/16 22:53
*
* @author Shengzhao Li
* @since 3.0.0
*/
class PKCEUtilsTest {
@Test
void generateCodeVerifier() {
String verifier = PKCEUtils.generateCodeVerifier();
assertNotNull(verifier);
assertTrue(verifier.length() >= 32);
}
@Test
void generateCodeChallenge() {
String verifier = PKCEUtils.generateCodeVerifier();
assertNotNull(verifier);
String challenge = PKCEUtils.generateCodeChallenge(verifier);
assertNotNull(challenge);
}
/**
* PKCE
* code_challenge_method : S256 (alg: SHA-256)
* code_verifier : base64 encode 32
* code_challenge : code_verifier 使(digest)base encode
*
* @throws Exception e
*/
@Test
void pkceFlow() {
// 1. 随机生成code_verifier
String codeVerifier = PKCEUtils.generateCodeVerifier();
// System.out.println("code_verifier -> " + codeVerifier);
//2. 按指定算法计算 挑战码 code_challenge
String codeChallenge = PKCEUtils.generateCodeChallenge(codeVerifier);
assertNotNull(codeChallenge);
// System.out.println("code_challenge -> " + codeChallenge);
}
}
Loading…
Cancel
Save