Code Challenge
In order to utilize the Authorize APIs, generating a Code Challenge is necessary. This challenge is derived from a Code Verifier, a cryptographically random string that should be between 43 and 128 characters long.
Amazon Pay Later generates a Secure Hash Algorithm 256-bit (SHA-256) hashed code challenge and uses a code verifier to authorize APIs.
Code Verifier Generation
To generate a Code Verifier, use the following method:
static final String CHARACTER_SET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~ _.";
private static final int LENGTH = 128;
public static String generateCodeVerifier() {
String codeVerifier = RandomStringUtils.random(
LENGTH, 0, CHARACTER_SET.length() - 1,
false, false, CHARACTER_SET.toCharArray(), new SecureRandom());
return codeVerifier;
}
Code Challenge Generation
To create a Code Challenge from the Code Verifier, use the following method:
private static final String SHA_256 = "SHA256";
public static String generateCodeChallenge(String codeVerifier) {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance(SHA_256);
}
catch (NoSuchAlgorithmException e) {
// Handle exception
}
final byte[] digestArr = digest.digest(codeVerifier.getBytes(Charset.defaultCharset()));
return base64UrlEncode(digestArr);
}
private static String base64UrlEncode(final byte[] arg) {
String s = Base64.encodeToString(arg, Base64.DEFAULT);
// Regular base64 encoder
s = s.split("=")[0]; // Remove any trailing '='s
s = s.replace('+', '-'); // 62nd char of encoding
s = s.replace('/', '_'); // 63rd char of encoding
return s;
}