Skip to content

Commit

Permalink
Calculate padding instead of fixed one
Browse files Browse the repository at this point in the history
  • Loading branch information
banterCZ committed Jan 2, 2024
1 parent e6d0ac8 commit 86fb089
Showing 1 changed file with 28 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,6 @@ public class IdentifierGenerator {
*/
private static final int ACTIVATION_CODE_BYTES_LENGTH = 12;

/**
* When {@code ACTIVATION_CODE_BYTES_LENGTH = 12}, the Base32 padding is always {@code ====}.
*/
private static final String ACTIVATION_CODE_PADDING = "====";

/**
* Default length of random bytes used for Activation Code.
* See {@link #generateActivationCode()} method for details.
Expand Down Expand Up @@ -164,8 +159,8 @@ public boolean validateActivationCode(String activationCode) {
return false;
}

// The activation code does not contain the padding, but it must be present in the Base32 value to be valid.
byte[] activationCodeBytes = Base32.decode(activationCode.replace("-", "") + ACTIVATION_CODE_PADDING);
final String activationCodeBase32 = fetchActivationCodeBase32(activationCode);
final byte[] activationCodeBytes = Base32.decode(activationCodeBase32);

// Verify byte array length
if (activationCodeBytes.length != ACTIVATION_CODE_BYTES_LENGTH) {
Expand All @@ -184,6 +179,32 @@ public boolean validateActivationCode(String activationCode) {
return expectedChecksum == actualChecksum;
}

/**
* Remove hyphens and calculate padding.
* <p>
* When {@code ACTIVATION_CODE_BYTES_LENGTH = 12}, the Base32 padding is always {@code ====}, but this method is safe to change the length in the future.
*
* @param activationCode activation code with hyphens
* @return base32 with padding
*/
private static String fetchActivationCodeBase32(final String activationCode) {
final String activationCodeWithoutHyphens = activationCode.replace("-", "");
// The activation code does not contain the padding, but it must be present in the Base32 value to be valid.
final String activationCodePadding = switch (activationCodeWithoutHyphens.length() % 8) {
case 2:
yield "======";
case 4:
yield "====";
case 5:
yield "===";
case 7:
yield "=";
default:
yield "";
};
return activationCodeWithoutHyphens + activationCodePadding;
}

/**
* Generate recovery code and PUK.
* @return Recovery code and PUK.
Expand Down

0 comments on commit 86fb089

Please sign in to comment.