|
| 1 | +package com.genexus.gam.utils; |
| 2 | + |
| 3 | + |
| 4 | +import org.apache.logging.log4j.LogManager; |
| 5 | +import org.apache.logging.log4j.Logger; |
| 6 | +import org.bouncycastle.crypto.Digest; |
| 7 | +import org.bouncycastle.crypto.digests.SHA256Digest; |
| 8 | +import org.bouncycastle.util.encoders.UrlBase64; |
| 9 | + |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | +import java.text.MessageFormat; |
| 12 | + |
| 13 | +@SuppressWarnings("LoggingSimilarMessage") |
| 14 | +public class Pkce { |
| 15 | + |
| 16 | + private static final Logger logger = LogManager.getLogger(Pkce.class); |
| 17 | + |
| 18 | + public static String create(int len, String option) { |
| 19 | + logger.trace("create"); |
| 20 | + String code_verifier = Random.alphanumeric(len); |
| 21 | + switch (option.toUpperCase().trim()) { |
| 22 | + case "S256": |
| 23 | + byte[] digest = hash(new SHA256Digest(), code_verifier.getBytes(StandardCharsets.UTF_8)); |
| 24 | + return MessageFormat.format("{0},{1}", code_verifier.trim(), new String(UrlBase64.encode(digest))); |
| 25 | + case "PLAIN": |
| 26 | + return MessageFormat.format("{0},{1}", code_verifier.trim(), Encoding.toBase64Url(code_verifier.trim())); |
| 27 | + default: |
| 28 | + logger.error("Unknown PKCE option"); |
| 29 | + return ""; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public static boolean verify(String code_verifier, String code_challenge, String option) { |
| 34 | + logger.trace("verify"); |
| 35 | + switch (option.toUpperCase().trim()) { |
| 36 | + case "S256": |
| 37 | + byte[] digest = hash(new SHA256Digest(), code_verifier.trim().getBytes(StandardCharsets.UTF_8)); |
| 38 | + return (new String(UrlBase64.encode(digest))).equals(code_challenge.trim()); |
| 39 | + case "PLAIN": |
| 40 | + byte[] bytes_plain = UrlBase64.decode(code_challenge.trim().getBytes(StandardCharsets.UTF_8)); |
| 41 | + return new String(bytes_plain).equals(code_verifier.trim()); |
| 42 | + default: |
| 43 | + logger.error("Unknown PKCE option"); |
| 44 | + return false; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + private static byte[] hash(Digest digest, byte[] inputBytes) { |
| 49 | + byte[] retValue = new byte[digest.getDigestSize()]; |
| 50 | + digest.update(inputBytes, 0, inputBytes.length); |
| 51 | + digest.doFinal(retValue, 0); |
| 52 | + return retValue; |
| 53 | + } |
| 54 | +} |
0 commit comments