diff --git a/README.md b/README.md
index ac6dda95e..2956cc916 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ OWASP® ESAPI (The OWASP Enterprise Security API) is a free, open source, web ap
# Jakarta EE Support
**IMPORTANT:**
ESAPI has supported the Jakarta Servlet API (i.e., **jakarta.servlet.api**) since release
-2.5.3.0. (Unfortunately, we were just forgot to note that in this **README** file. Duh!)
+2.5.3.0. (Unfortunately, this information was previously missing in this **README** file.)
Therefore, for release 2.5.3.0 and later versions of ESAPI, ESAPI ought to be able to support Spring Boot 3, Spring 6, Tomcat 10,
and other applications or libraries requiring Jarkata EE. (If you find a case where it does
diff --git a/src/main/java/org/owasp/esapi/Authenticator.java b/src/main/java/org/owasp/esapi/Authenticator.java
index e113b0bdd..4e83903d5 100644
--- a/src/main/java/org/owasp/esapi/Authenticator.java
+++ b/src/main/java/org/owasp/esapi/Authenticator.java
@@ -148,7 +148,7 @@ public interface Authenticator {
*
* WARNING: The implementation of this method as defined in the
* default reference implementation class, {@code FileBasedAuthenticator},
- * uses a password hash algorthim that is known to be weak. You are advised
+ * uses a password hash algorithm that is known to be weak. You are advised
* to replace the default reference implementation class with your own custom
* implementation that uses a stronger password hashing algorithm.
* See class comments in * {@code FileBasedAuthenticator} for further details.
diff --git a/src/main/java/org/owasp/esapi/ESAPI.java b/src/main/java/org/owasp/esapi/ESAPI.java
index ef389d020..c42a21ff8 100644
--- a/src/main/java/org/owasp/esapi/ESAPI.java
+++ b/src/main/java/org/owasp/esapi/ESAPI.java
@@ -93,7 +93,7 @@ public static Authenticator authenticator() {
}
/**
- * The ESAPI Encoder is primarilly used to provide output encoding to
+ * The ESAPI Encoder is primarily used to provide output encoding to
* prevent Cross-Site Scripting (XSS).
* @return the current ESAPI Encoder object being used to encode and decode data for this application.
*/
diff --git a/src/main/java/org/owasp/esapi/Encoder.java b/src/main/java/org/owasp/esapi/Encoder.java
index 22ae8f94b..ad4950dc9 100644
--- a/src/main/java/org/owasp/esapi/Encoder.java
+++ b/src/main/java/org/owasp/esapi/Encoder.java
@@ -519,7 +519,7 @@ public interface Encoder {
*
* NB: The reference implementation encodes almost everything and may over-encode.
*
- * The difficulty with XPath encoding is that XPath has no built in mechanism for escaping
+ * The difficulty with XPath encoding is that XPath has no built-in mechanism for escaping
* characters. It is possible to use XQuery in a parameterized way to
* prevent injection.
*
diff --git a/src/main/java/org/owasp/esapi/Encryptor.java b/src/main/java/org/owasp/esapi/Encryptor.java
index 28bb896a3..2333da821 100644
--- a/src/main/java/org/owasp/esapi/Encryptor.java
+++ b/src/main/java/org/owasp/esapi/Encryptor.java
@@ -162,8 +162,8 @@ CipherText encrypt(SecretKey key, PlainText plaintext)
*
* @param ciphertext The {@code CipherText} object to be decrypted.
* @return The {@code PlainText} object resulting from decrypting the specified
- * ciphertext. Note that it it is desired to convert the returned
- * plaintext byte array to a Java String is should be done using
+ * ciphertext. Note that the returned plaintext byte array
+ * should be converted to a Java String using
* {@code new String(byte[], "UTF-8");} rather than simply using
* {@code new String(byte[]);} which uses native encoding and may
* not be portable across hardware and/or OS platforms.
@@ -186,8 +186,8 @@ CipherText encrypt(SecretKey key, PlainText plaintext)
* @param key The {@code SecretKey} to use for encrypting the plaintext.
* @param ciphertext The {@code CipherText} object to be decrypted.
* @return The {@code PlainText} object resulting from decrypting the specified
- * ciphertext. Note that it it is desired to convert the returned
- * plaintext byte array to a Java String is should be done using
+ * ciphertext. Note that the returned plaintext byte array
+ * should be converted to a Java String using
* {@code new String(byte[], "UTF-8");} rather than simply using
* {@code new String(byte[]);} which uses native encoding and may
* not be portable across hardware and/or OS platforms.
diff --git a/src/main/java/org/owasp/esapi/HTTPUtilities.java b/src/main/java/org/owasp/esapi/HTTPUtilities.java
index 9cdfc36b0..582f1a1b7 100644
--- a/src/main/java/org/owasp/esapi/HTTPUtilities.java
+++ b/src/main/java/org/owasp/esapi/HTTPUtilities.java
@@ -377,7 +377,7 @@ public interface HTTPUtilities
* everything to keey your application and environment secure. Some of the more obvious omissions are the
* absence of examining the actual file content to determine the actual file type or running some AV scan
* on the uploaded files. You have to add that functionality to you if you want or need that. Some
- * reasource that you may find usefule are:
+ * resource that you may find useful are:
*
diff --git a/src/main/java/org/owasp/esapi/Logger.java b/src/main/java/org/owasp/esapi/Logger.java
index 288509b92..b0a5b7ccc 100644
--- a/src/main/java/org/owasp/esapi/Logger.java
+++ b/src/main/java/org/owasp/esapi/Logger.java
@@ -89,9 +89,9 @@
* the basis for its logging implementation. Both provided implementations implement requirements #1 through #5 above.
*
* Customization: It is expected that most organizations may wish to implement their own custom {@code Logger} class in
- * order to integrate ESAPI logging with their specific logging infrastructure. The ESAPI feference implementations
+ * order to integrate ESAPI logging with their specific logging infrastructure. The ESAPI reference implementations
* can serve as a useful starting point to intended to provide a simple functional example of an implementation, but
- * they are also largely usuable out-of-the-box with some additional minimal log configuration.
+ * they are also largely usable out-of-the-box with some additional minimal log configuration.
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) Aspect Security
diff --git a/src/main/java/org/owasp/esapi/SafeFile.java b/src/main/java/org/owasp/esapi/SafeFile.java
index e048e9419..da791c6f5 100644
--- a/src/main/java/org/owasp/esapi/SafeFile.java
+++ b/src/main/java/org/owasp/esapi/SafeFile.java
@@ -62,12 +62,12 @@ public SafeFile(URI uri) throws ValidationException {
private void doDirCheck(String path) throws ValidationException {
Matcher m1 = DIR_BLACKLIST_PAT.matcher( path );
- if ( null != m1 && m1.find() ) {
+ if ( m1.find() ) {
throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains illegal character: " + m1.group() );
}
Matcher m2 = PERCENTS_PAT.matcher( path );
- if (null != m2 && m2.find() ) {
+ if ( m2.find() ) {
throw new ValidationException( "Invalid directory", "Directory path (" + path + ") contains encoded characters: " + m2.group() );
}
diff --git a/src/main/java/org/owasp/esapi/SecurityConfiguration.java b/src/main/java/org/owasp/esapi/SecurityConfiguration.java
index 564206de0..e0b529b49 100644
--- a/src/main/java/org/owasp/esapi/SecurityConfiguration.java
+++ b/src/main/java/org/owasp/esapi/SecurityConfiguration.java
@@ -179,7 +179,7 @@ public interface SecurityConfiguration extends EsapiPropertyLoader {
* considered the default key size that ESAPI will use for symmetric
* ciphers supporting multiple key sizes. (Note that there is also an Encryptor.MinEncryptionKeyLength,
* which is the minimum key size (in bits) that ESAPI will support
- * for encryption. (There is no miminimum for decryption.)
+ * for encryption. (There is no minimum for decryption.)
*
* @return the key length (in bits)
* @deprecated Use SecurityConfiguration.getIntProp("appropriate_esapi_prop_name") instead.
diff --git a/src/main/java/org/owasp/esapi/StringUtilities.java b/src/main/java/org/owasp/esapi/StringUtilities.java
index 55f8c55a3..24b06e64f 100644
--- a/src/main/java/org/owasp/esapi/StringUtilities.java
+++ b/src/main/java/org/owasp/esapi/StringUtilities.java
@@ -90,14 +90,14 @@ public static boolean contains(StringBuilder input, char c) {
}
/**
- * Returns the replace value if the value of test is null, "null", or ""
+ * Returns the replace value if the value of test is null, "null" (case-insensitive), or blank
*
* @param test The value to test
* @param replace The replacement value
* @return The correct value
*/
public static String replaceNull( String test, String replace ) {
- return test == null || "null".equalsIgnoreCase( test.trim() ) || "".equals( test.trim() ) ? replace : test;
+ return test == null || "null".equalsIgnoreCase( test.trim() ) || test.trim().isEmpty() ? replace : test;
}
/**
@@ -185,9 +185,9 @@ public static int getLevenshteinDistance (String s, String t) {
*/
public static boolean notNullOrEmpty(String str, boolean trim) {
if ( trim ) {
- return !( str == null || str.trim().equals("") );
+ return !( str == null || str.trim().isEmpty() );
} else {
- return !( str == null || str.equals("") );
+ return !( str == null || str.isEmpty() );
}
}
@@ -195,6 +195,6 @@ public static boolean notNullOrEmpty(String str, boolean trim) {
* Returns true if String is empty ("") or null.
*/
public static boolean isEmpty(String str) {
- return str == null || str.length() == 0;
+ return str == null || str.isEmpty();
}
}
diff --git a/src/main/java/org/owasp/esapi/User.java b/src/main/java/org/owasp/esapi/User.java
index 6c29b4f59..eeb765d7c 100644
--- a/src/main/java/org/owasp/esapi/User.java
+++ b/src/main/java/org/owasp/esapi/User.java
@@ -380,7 +380,7 @@ public interface User extends Principal, Serializable {
/**
* Set the time of the last failed login for this user.
*
- * @param lastFailedLoginTime the date and time when the user just failed to login correctly.
+ * @param lastFailedLoginTime the date and time when the user just failed to log in correctly.
*/
void setLastFailedLoginTime(Date lastFailedLoginTime);
diff --git a/src/main/java/org/owasp/esapi/Validator.java b/src/main/java/org/owasp/esapi/Validator.java
index c662daaa1..be16fbf50 100644
--- a/src/main/java/org/owasp/esapi/Validator.java
+++ b/src/main/java/org/owasp/esapi/Validator.java
@@ -384,10 +384,10 @@ public interface Validator {
boolean isValidSafeHTML(String context, String input, int maxLength, boolean allowNull, ValidationErrorList errorList) throws IntrusionException;
/**
- * Canonicalize and then sanitize the input so that it is "safe" for renderinger in an HTML context (i.e., that
+ * Canonicalize and then sanitize the input so that it is "safe" for rendering in an HTML context (i.e., that
* it does not contain unwanted scripts in the body, attributes, CSS, URLs, or anywhere else). Note that the resulting
* returned value may omit input that is considered dangerous and cannot be safely sanitized and other input
- * that gets HTML encoded (e.g., a single quote (') might get chaged to """).
+ * that gets HTML encoded (e.g., a single quote (') might get changed to """).
*
* The default behavior of this check depends on the {@code antisamy-esapi.xml} AntiSamy policy configuration file
* (or an alternate filename, specified via the "Validator.HtmlValidationConfigurationFile" property in your
@@ -414,10 +414,10 @@ public interface Validator {
String getValidSafeHTML(String context, String input, int maxLength, boolean allowNull) throws ValidationException, IntrusionException;
/**
- * Canonicalize and then sanitize the input so that it is "safe" for renderinger in an HTML context (i.e., that
+ * Canonicalize and then sanitize the input so that it is "safe" for rendering in an HTML context (i.e., that
* it does not contain unwanted scripts in the body, attributes, CSS, URLs, or anywhere else). Note that the resulting
* returned value may omit input that is considered dangerous and cannot be safely sanitized and other input
- * that gets HTML encoded (e.g., a single quote (') might get chaged to """).
+ * that gets HTML encoded (e.g., a single quote (') might get changed to """).
*
* The default behavior of this check depends on the {@code antisamy-esapi.xml} AntiSamy policy configuration file
* (or an alternate filename, specified via the "Validator.HtmlValidationConfigurationFile" property in your
diff --git a/src/main/java/org/owasp/esapi/codecs/AbstractCodec.java b/src/main/java/org/owasp/esapi/codecs/AbstractCodec.java
index 77c153fcd..5149b5d0a 100644
--- a/src/main/java/org/owasp/esapi/codecs/AbstractCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/AbstractCodec.java
@@ -25,7 +25,7 @@
*
* Be sure to see the several WARNINGs associated with the detailed
* method descriptions. You will not find that in the "Method Summary" section
- * of the javadoc because that only shows the intial sentence.
+ * of the javadoc because that only shows the initial sentence.
*
* @author Jeff Williams (jeff.williams .at. aspectsecurity.com) Aspect Security
@@ -96,7 +96,7 @@ public String encodeCharacter( char[] immune, Character c ) {
/**
- * To prevent accidental footgun usage and calling
+ * To prevent accidental usage and calling
* {@link #encodeCharacter( char[], int)} when called with {@code char} and
* {@code char} is first silently converted to {@code int} and then the
* unexpected method is called.
diff --git a/src/main/java/org/owasp/esapi/codecs/AbstractPushbackSequence.java b/src/main/java/org/owasp/esapi/codecs/AbstractPushbackSequence.java
index f90e07dbb..2562a8441 100644
--- a/src/main/java/org/owasp/esapi/codecs/AbstractPushbackSequence.java
+++ b/src/main/java/org/owasp/esapi/codecs/AbstractPushbackSequence.java
@@ -19,7 +19,7 @@
/**
* This Abstract class provides the generic logic for using a {@link PushbackSequence}
- * in regards to iterating strings. The final Impl is intended for the user to supply
+ * in regard to iterating strings. The final Impl is intended for the user to supply
* a type T such that the pushback interface can be utilized for sequences
* of type T. Presently this generic class is limited by the fact that
* input is a String.
@@ -61,7 +61,7 @@ public boolean hasNext() {
return true;
if (input == null)
return false;
- if (input.length() == 0)
+ if (input.isEmpty())
return false;
if (index >= input.length())
return false;
diff --git a/src/main/java/org/owasp/esapi/codecs/Base64.java b/src/main/java/org/owasp/esapi/codecs/Base64.java
index 1af941510..00bae0c43 100644
--- a/src/main/java/org/owasp/esapi/codecs/Base64.java
+++ b/src/main/java/org/owasp/esapi/codecs/Base64.java
@@ -3,6 +3,8 @@
import org.owasp.esapi.ESAPI;
import org.owasp.esapi.Logger;
+import java.io.IOException;
+
// CHECKME: Version at http://iharder.net/base64 is up to v2.3.3. Some semantic changes
// starting with v2.3. Should we upgrade and then add ESAPI logging or stay at 2.2.2 base?
// I think that really depends on how much OWASP ESAPI plans on tracking changes to this
@@ -72,7 +74,7 @@
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).
- *
v1.5 - Output stream pases on flush() command but doesn't do anything itself.
+ *
v1.5 - Output stream passes on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.
*
v1.4 - Added helper methods to read/write files.
@@ -363,7 +365,7 @@ public class Base64
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
- private final static byte[] getAlphabet( int options )
+ private static byte[] getAlphabet( int options )
{
if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_ALPHABET;
else if( (options & ORDERED) == ORDERED ) return _ORDERED_ALPHABET;
@@ -379,7 +381,7 @@ private final static byte[] getAlphabet( int options )
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
- private final static byte[] getDecodabet( int options )
+ private static byte[] getDecodabet( int options )
{
if( (options & URL_SAFE) == URL_SAFE ) return _URL_SAFE_DECODABET;
else if( (options & ORDERED) == ORDERED ) return _ORDERED_DECODABET;
@@ -396,7 +398,7 @@ private Base64(){}
* if you're embedding this code into a larger program.
* @param args
*/
- public final static void main( String[] args )
+ public static void main( String[] args )
{
if( args.length < 3 ){
usage("Not enough arguments.");
@@ -422,7 +424,7 @@ else if( flag.equals( "-d" ) ) {
*
* @param msg A message to include with usage info.
*/
- private final static void usage( String msg )
+ private static void usage( String msg )
{
System.err.println( msg );
System.err.println( "Usage: java Base64 -e|-d inputfile outputfile" );
@@ -458,7 +460,7 @@ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes,
* anywhere along their length by specifying
* srcOffset and destOffset.
* This method does not check to make sure your arrays
- * are large enough to accomodate srcOffset + 3 for
+ * are large enough to accommodate srcOffset + 3 for
* the source array or destOffset + 4 for
* the destination array.
* The actual number of significant bytes in your array is
@@ -706,7 +708,7 @@ public static String encodeBytes( byte[] source, int off, int len, int options )
* anywhere along their length by specifying
* srcOffset and destOffset.
* This method does not check to make sure your arrays
- * are large enough to accomodate srcOffset + 4 for
+ * are large enough to accommodate srcOffset + 4 for
* the source array or destOffset + 3 for
* the destination array.
* This method returns the actual number of bytes that
@@ -830,34 +832,32 @@ public static byte[] decode( byte[] source, int off, int len, int options )
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
- for( i = off; i < off+len; i++ )
- {
+ for (i = off; i < off+len; i++) {
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ];
- if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
- {
- if( sbiDecode >= EQUALS_SIGN_ENC )
- {
- b4[ b4Posn++ ] = sbiCrop;
- if( b4Posn > 3 )
- {
- outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
- b4Posn = 0;
+ if (sbiDecode < WHITE_SPACE_ENC) {
+ logger.error( Logger.SECURITY_FAILURE, "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
+ return null;
+ }
- // If that was the equals sign, break out of 'for' loop
- if( sbiCrop == EQUALS_SIGN )
- break;
- } // end if: quartet built
+ if (sbiDecode < EQUALS_SIGN_ENC) {
+ continue;
+ }
- } // end if: equals sign or better
+ b4[ b4Posn++ ] = sbiCrop;
+ if (b4Posn <= 3) {
+ continue;
+ }
+
+ outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
+ b4Posn = 0;
+
+ // If that was the equals sign, break out of 'for' loop
+ if (sbiCrop == EQUALS_SIGN) {
+ break;
+ }
- } // end if: white space, equals sign or better
- else
- {
- logger.error( Logger.SECURITY_FAILURE, "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
- return null;
- } // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
@@ -1267,117 +1267,112 @@ public InputStream( java.io.InputStream in, int options )
public int read() throws java.io.IOException
{
// Do we need to get data?
- if( position < 0 )
- {
- if( encode )
- {
- byte[] b3 = new byte[3];
- int numBinaryBytes = 0;
- for( int i = 0; i < 3; i++ )
- {
- try
- {
- int b = in.read();
-
- // If end of stream, b is -1.
- if( b >= 0 )
- {
- b3[i] = (byte)b;
- numBinaryBytes++;
- } // end if: not end of stream
-
- } // end try: read
- catch( java.io.IOException e )
- {
- // Only a problem if we got no data at all.
- if( i == 0 )
- throw e;
-
- } // end catch
- } // end for: each needed input byte
-
- if( numBinaryBytes > 0 )
- {
- encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
- position = 0;
- numSigBytes = 4;
- } // end if: got data
- else
- {
- return -1;
- } // end else
- } // end if: encoding
+ if( position < 0 ) {
+ Integer data = encode ? encode() : decode();
+ if (data != null) return data;
+ }
- // Else decoding
- else
- {
- byte[] b4 = new byte[4];
- int i = 0;
- for( i = 0; i < 4; i++ )
- {
- // Read four "meaningful" bytes:
- int b = 0;
- do{ b = in.read(); }
- while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
+ // Got data?
+ if (position < 0) {
+ // When JDK1.4 is more accepted, use an assertion here.
+ throw new IOException( "Error in Base64 code reading stream." );
+ }
- if( b < 0 )
- break; // Reads a -1 if end of stream
+ // End of relevant data?
+ if (/*!encode &&*/ position >= numSigBytes) {
+ return -1;
+ }
- b4[i] = (byte)b;
- } // end for: each needed input byte
+ if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {
+ lineLength = 0;
+ return '\n';
+ }
- if( i == 4 )
- {
- numSigBytes = decode4to3( b4, 0, buffer, 0, options );
- position = 0;
- } // end if: got four characters
- else if( i == 0 ){
- return -1;
- } // end else if: also padded correctly
- else
- {
- // Must have broken out from above.
- throw new java.io.IOException( "Improperly padded Base64 input." );
- } // end
+ lineLength++; // This isn't important when decoding
+ // but throwing an extra "if" seems
+ // just as wasteful.
- } // end else: decode
- } // end else: get data
+ int b = buffer[ position++ ];
- // Got data?
- if( position >= 0 )
- {
- // End of relevant data?
- if( /*!encode &&*/ position >= numSigBytes )
- return -1;
+ if (position >= bufferLength) {
+ position = -1;
+ }
- if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
- {
- lineLength = 0;
- return '\n';
- } // end if
- else
+ return b & 0xFF; // This is how you "cast" a byte that's
+ // intended to be unsigned.
+
+ } // end read
+
+ private Integer encode() throws java.io.IOException {
+ byte[] b3 = new byte[3];
+ int numBinaryBytes = 0;
+ for( int i = 0; i < 3; i++ )
+ {
+ try
{
- lineLength++; // This isn't important when decoding
- // but throwing an extra "if" seems
- // just as wasteful.
+ int b = in.read();
- int b = buffer[ position++ ];
+ // If end of stream, b is -1.
+ if( b >= 0 )
+ {
+ b3[i] = (byte)b;
+ numBinaryBytes++;
+ } // end if: not end of stream
- if( position >= bufferLength )
- position = -1;
+ } // end try: read
+ catch( java.io.IOException e )
+ {
+ // Only a problem if we got no data at all.
+ if( i == 0 )
+ throw e;
- return b & 0xFF; // This is how you "cast" a byte that's
- // intended to be unsigned.
- } // end else
- } // end if: position >= 0
+ } // end catch
+ } // end for: each needed input byte
- // Else error
+ if( numBinaryBytes > 0 )
+ {
+ encode3to4( b3, 0, numBinaryBytes, buffer, 0, options );
+ position = 0;
+ numSigBytes = 4;
+ } // end if: got data
else
{
- // When JDK1.4 is more accepted, use an assertion here.
- throw new java.io.IOException( "Error in Base64 code reading stream." );
+ return -1;
} // end else
- } // end read
+ return null;
+ }
+
+ private Integer decode() throws java.io.IOException {
+ byte[] b4 = new byte[4];
+ int i = 0;
+ for( i = 0; i < 4; i++ )
+ {
+ // Read four "meaningful" bytes:
+ int b = 0;
+ do{ b = in.read(); }
+ while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC );
+
+ if( b < 0 )
+ break; // Reads a -1 if end of stream
+
+ b4[i] = (byte)b;
+ } // end for: each needed input byte
+
+ if( i == 4 )
+ {
+ numSigBytes = decode4to3( b4, 0, buffer, 0, options );
+ position = 0;
+ } // end if: got four characters
+ else if( i == 0 ){
+ return -1;
+ } // end else if: also padded correctly
+ else
+ {
+ // Must have broken out from above.
+ throw new java.io.IOException( "Improperly padded Base64 input." );
+ } // end
+ return null;
+ }
/**
* Calls {@link #read()} repeatedly until the end of stream
@@ -1498,55 +1493,58 @@ public OutputStream( java.io.OutputStream out, int options )
* @throws java.io.IOException
* @since 1.3
*/
- public void write(int theByte) throws java.io.IOException
- {
- // Encoding suspended?
- if( suspendEncoding )
- {
+ public void write(int theByte) throws java.io.IOException {
+ if( suspendEncoding ) {
super.out.write( theByte );
return;
- } // end if: supsended
+ }
- // Encode?
- if( encode )
- {
- buffer[ position++ ] = (byte)theByte;
- if( position >= bufferLength ) // Enough to encode.
- {
- out.write( encode3to4( b4, buffer, bufferLength, options ) );
+ if( encode ) {
+ encode(theByte);
+ } else {
+ decode(theByte);
+ }
+ } // end write
- lineLength += 4;
- if( breakLines && lineLength >= MAX_LINE_LENGTH )
- {
- out.write( NEW_LINE );
- lineLength = 0;
- } // end if: end of line
+ private void encode(int theByte) throws IOException {
+ buffer[ position++ ] = (byte) theByte;
- position = 0;
- } // end if: enough to output
- } // end if: encoding
+ if (position < bufferLength) {
+ // not enough to encode.
+ return;
+ }
- // Else, Decoding
- else
- {
- // Meaningful Base64 character?
- if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC )
- {
- buffer[ position++ ] = (byte)theByte;
- if( position >= bufferLength ) // Enough to output.
- {
- int len = Base64.decode4to3( buffer, 0, b4, 0, options );
- out.write( b4, 0, len );
- //out.write( Base64.decode4to3( buffer ) );
- position = 0;
- } // end if: enough to output
- } // end if: meaningful base64 character
- else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC )
- {
- throw new java.io.IOException( "Invalid character in Base64 data." );
- } // end else: not white space either
- } // end else: decoding
- } // end write
+ out.write( encode3to4( b4, buffer, bufferLength, options ) );
+
+ lineLength += 4;
+ if( breakLines && lineLength >= MAX_LINE_LENGTH ) {
+ out.write( NEW_LINE );
+ lineLength = 0;
+ }
+
+ position = 0;
+ }
+
+ private void decode(int theByte) throws IOException {
+ // Meaningful Base64 character?
+ if(decodabet[ theByte & 0x7f ] < WHITE_SPACE_ENC) {
+ throw new IOException( "Invalid character in Base64 data." );
+ }
+
+ if (decodabet[theByte & 0x7f] == WHITE_SPACE_ENC) {
+ return;
+ }
+
+ buffer[ position++ ] = (byte) theByte;
+ if (position < bufferLength) {
+ // not enough to output
+ return;
+ }
+ int len = Base64.decode4to3( buffer, 0, b4, 0, options );
+ out.write( b4, 0, len );
+ //out.write( Base64.decode4to3( buffer ) );
+ position = 0;
+ }
/**
* Calls {@link #write(int)} repeatedly until len
@@ -1581,18 +1579,16 @@ public void write( byte[] theBytes, int off, int len ) throws java.io.IOExceptio
*/
public void flushBase64() throws java.io.IOException
{
- if( position > 0 )
- {
- if( encode )
- {
- out.write( encode3to4( b4, buffer, position, options ) );
- position = 0;
- } // end if: encoding
- else
- {
- throw new java.io.IOException( "Base64 input not properly padded." );
- } // end else: decoding
- } // end if: buffer partially full
+ if (position <= 0) {
+ // buffer partially full
+ return;
+ }
+ if( encode ) {
+ out.write( encode3to4( b4, buffer, position, options ) );
+ position = 0;
+ } else {
+ throw new java.io.IOException( "Base64 input not properly padded." );
+ }
} // end flush
diff --git a/src/main/java/org/owasp/esapi/codecs/CSSCodec.java b/src/main/java/org/owasp/esapi/codecs/CSSCodec.java
index 9ffb60f32..d68cc1f1d 100644
--- a/src/main/java/org/owasp/esapi/codecs/CSSCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/CSSCodec.java
@@ -147,7 +147,7 @@ public Character decodeCharacter(PushbackSequence input)
switch(second)
{ // special whitespace cases. I assume they mean
// for all of these to qualify as a "new
- // line." Otherwise there is no specification
+ // line." Otherwise, there is no specification
// of what to do for \f
case '\r':
if(input.peek('\n'))
diff --git a/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java b/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java
index 84ccb2ca5..30856adc3 100644
--- a/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/HTMLEntityCodec.java
@@ -99,7 +99,7 @@ public String encodeCharacter( char[] immune, int codePoint ) {
&& codePoint != '\r' )
|| ( codePoint >= 0x7f && codePoint <= 0x9f ) )
{
- hex = REPLACEMENT_HEX; // Let's entity encode this instead of returning it
+ hex = REPLACEMENT_HEX; // Lets entity encode this instead of returning it
codePoint = REPLACEMENT_CHAR;
}
@@ -119,7 +119,7 @@ public String encodeCharacter( char[] immune, int codePoint ) {
* Returns the decoded version of the character starting at index, or
* null if no decoding is possible.
*
- * Formats all are legal both with and without semi-colon, upper/lower case:
+ * Formats all are legal both with and without semicolon, upper/lower case:
* dddd;
* hhhh;
* &name;
@@ -198,7 +198,7 @@ private Integer parseNumber( PushbackSequence input ) {
sb.appendCodePoint( c );
input.next();
- // if character is a semi-colon, eat it and quit
+ // if character is a semicolon, eat it and quit
} else if (c == ';' ) {
input.next();
break;
@@ -239,7 +239,7 @@ private Integer parseHex( PushbackSequence input ) {
sb.appendCodePoint( c );
input.next();
- // if character is a semi-colon, eat it and quit
+ // if character is a semicolon, eat it and quit
} else if (c == ';' ) {
input.next();
break;
@@ -312,7 +312,7 @@ private Integer getNamedEntity( PushbackSequence input ) {
for(int i=0;i input ) {
}
/**
- * Build a unmodifiable Map from entity Character to Name.
+ * Build an unmodifiable Map from entity Character to Name.
* @return Unmodifiable map.
*/
private static synchronized Map mkCharacterToEntityMap()
@@ -584,7 +584,7 @@ private static synchronized Map mkCharacterToEntityMap()
}
/**
- * Build a unmodifiable Trie from entitiy Name to Character
+ * Build an unmodifiable Trie from entity Name to Character
* @return Unmodifiable trie.
*/
private static synchronized Trie mkEntityToCharacterTrie()
diff --git a/src/main/java/org/owasp/esapi/codecs/HashTrie.java b/src/main/java/org/owasp/esapi/codecs/HashTrie.java
index b72b8c1fe..f290cdd79 100644
--- a/src/main/java/org/owasp/esapi/codecs/HashTrie.java
+++ b/src/main/java/org/owasp/esapi/codecs/HashTrie.java
@@ -346,7 +346,7 @@ Set keySet(StringBuilder key, Set keys)
if(value != null)
// MUST toString here
keys.add(key.toString());
- if(nextMap != null && nextMap.size() > 0)
+ if(nextMap != null && !nextMap.isEmpty())
{
key.append('X');
for(Map.Entry> entry : nextMap.entrySet())
@@ -360,7 +360,7 @@ Set keySet(StringBuilder key, Set keys)
}
/**
- * Recursively build a entry set.
+ * Recursively build an entry set.
* @param key StringBuilder with our key.
* @param entries Set to add to
* @return entries with additions
@@ -372,7 +372,7 @@ Set> entrySet(StringBuilder key, Set 0)
+ if(nextMap != null && !nextMap.isEmpty())
{
key.append('X');
for(Map.Entry> entry : nextMap.entrySet())
@@ -396,7 +396,7 @@ public HashTrie()
}
/**
- * Get the key value entry who's key is the longest prefix match.
+ * Get the key value entry whose key is the longest prefix match.
* @param key The key to lookup
* @return Entry with the longest matching key.
*/
@@ -408,7 +408,7 @@ public Map.Entry getLongestMatch(CharSequence key)
}
/**
- * Get the key value entry who's key is the longest prefix match.
+ * Get the key value entry whose key is the longest prefix match.
* @param keyIn Pushback reader to read the key from. This should
* have a buffer at least as large as {@link #getMaxKeyLength()}
* or an IOException may be thrown backing up.
@@ -487,7 +487,7 @@ public T put(CharSequence key, T value) throws NullPointerException
}
/**
- * Remove a entry.
+ * Remove an entry.
* @return previous value
* @throws UnsupportedOperationException always.
*/
@@ -549,7 +549,7 @@ public T get(Object key)
/**
* Get the number of entries.
- * @return the number or entries.
+ * @return the number of entries.
*/
public int size()
{
diff --git a/src/main/java/org/owasp/esapi/codecs/JSONCodec.java b/src/main/java/org/owasp/esapi/codecs/JSONCodec.java
index 524b2faac..25b8b438c 100644
--- a/src/main/java/org/owasp/esapi/codecs/JSONCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/JSONCodec.java
@@ -96,7 +96,7 @@ public String encodeCharacter( char[] immune, int codePoint )
// WARNING!! Character based Codecs will only handle the byte range of 0-65535 (0x0-0xffff).
// Passing any data represented by a higher numerical value will result in a downcast thus
// destroying the original data with undefined results.
- if ( Character.isValidCodePoint( codePoint ) == false ) {
+ if ( !Character.isValidCodePoint(codePoint) ) {
// throw new IllegalArgumentException( "Invalid codepoint '" + String.format("0x%04X", codePoint) + "'." );
return "";
}
diff --git a/src/main/java/org/owasp/esapi/codecs/JavaScriptCodec.java b/src/main/java/org/owasp/esapi/codecs/JavaScriptCodec.java
index 39f2d6406..69efe91ac 100644
--- a/src/main/java/org/owasp/esapi/codecs/JavaScriptCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/JavaScriptCodec.java
@@ -112,27 +112,19 @@ public Character decodeCharacter( PushbackSequence input ) {
// \0 collides with the octal decoder and is non-standard
// if ( second.charValue() == '0' ) {
// return Character.valueOf( (char)0x00 );
- if (second == 'b' ) {
- return 0x08;
- } else if (second == 't' ) {
- return 0x09;
- } else if (second == 'n' ) {
- return 0x0a;
- } else if (second == 'v' ) {
- return 0x0b;
- } else if (second == 'f' ) {
- return 0x0c;
- } else if (second == 'r' ) {
- return 0x0d;
- } else if (second == '\"' ) {
- return 0x22;
- } else if (second == '\'' ) {
- return 0x27;
- } else if (second == '\\' ) {
- return 0x5c;
-
- // look for \\xXX format
- } else if ( Character.toLowerCase( second.charValue() ) == 'x' ) {
+ switch (second) {
+ case 'b': return 0x08;
+ case 't': return 0x09;
+ case 'n': return 0x0a;
+ case 'v': return 0x0b;
+ case 'f': return 0x0c;
+ case 'r': return 0x0d;
+ case '\"': return 0x22;
+ case '\'': return 0x27;
+ case '\\': return 0x5c;
+ }
+
+ if ( Character.toLowerCase( second.charValue() ) == 'x' ) {
// Search for exactly 2 hex digits following
StringBuilder sb = new StringBuilder();
for ( int i=0; i<2; i++ ) {
diff --git a/src/main/java/org/owasp/esapi/codecs/MySQLCodec.java b/src/main/java/org/owasp/esapi/codecs/MySQLCodec.java
index 193dfa208..12bbe3d9e 100644
--- a/src/main/java/org/owasp/esapi/codecs/MySQLCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/MySQLCodec.java
@@ -63,7 +63,7 @@ public class MySQLCodec extends AbstractCharacterCodec {
* please see the Manual at
* @link http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_ansi
*
- * Currently the only supported modes are:
+ * Currently, the only supported modes are:
* ANSI
* STANDARD
*/
@@ -174,19 +174,20 @@ private String encodeCharacterANSI( Character c ) {
* Encoded Character
*/
private String encodeCharacterMySQL( Character c ) {
- char ch = c.charValue();
- if ( ch == 0x00 ) return "\\0";
- if ( ch == 0x08 ) return "\\b";
- if ( ch == 0x09 ) return "\\t";
- if ( ch == 0x0a ) return "\\n";
- if ( ch == 0x0d ) return "\\r";
- if ( ch == 0x1a ) return "\\Z";
- if ( ch == 0x22 ) return "\\\"";
- if ( ch == 0x25 ) return "\\%";
- if ( ch == 0x27 ) return "\\'";
- if ( ch == 0x5c ) return "\\\\";
- if ( ch == 0x5f ) return "\\_";
- return "\\" + c;
+ switch (c) {
+ case 0x00: return "\\0";
+ case 0x08: return "\\b";
+ case 0x09: return "\\t";
+ case 0x0a: return "\\n";
+ case 0x0d: return "\\r";
+ case 0x1a: return "\\Z";
+ case 0x22: return "\\\"";
+ case 0x25: return "\\%";
+ case 0x27: return "\\'";
+ case 0x5c: return "\\\\";
+ case 0x5f: return "\\_";
+ default: return "\\" + c;
+ }
}
/**
@@ -195,7 +196,7 @@ private String encodeCharacterMySQL( Character c ) {
* Returns the decoded version of the character starting at index, or
* null if no decoding is possible.
*
- * Formats all are legal (case sensitive)
+ * Formats all are legal (case-sensitive)
* In ANSI_MODE '' decodes to '
* In MYSQL_MODE \x decodes to x (or a small list of specials)
*/
@@ -271,30 +272,19 @@ private Character decodeCharacterMySQL( PushbackSequence input ) {
return null;
}
- if ( second.charValue() == '0' ) {
- return Character.valueOf( (char)0x00 );
- } else if ( second.charValue() == 'b' ) {
- return Character.valueOf( (char)0x08 );
- } else if ( second.charValue() == 't' ) {
- return Character.valueOf( (char)0x09 );
- } else if ( second.charValue() == 'n' ) {
- return Character.valueOf( (char)0x0a );
- } else if ( second.charValue() == 'r' ) {
- return Character.valueOf( (char)0x0d );
- } else if ( second.charValue() == 'Z' ) {
- return Character.valueOf( (char)0x1a );
- } else if ( second.charValue() == '\"' ) {
- return Character.valueOf( (char)0x22 );
- } else if ( second.charValue() == '%' ) {
- return Character.valueOf( (char)0x25 );
- } else if ( second.charValue() == '\'' ) {
- return Character.valueOf( (char)0x27 );
- } else if ( second.charValue() == '\\' ) {
- return Character.valueOf( (char)0x5c );
- } else if ( second.charValue() == '_' ) {
- return Character.valueOf( (char)0x5f );
- } else {
- return second;
+ switch (second) {
+ case '0': return (char) 0x00;
+ case 'b': return (char) 0x08;
+ case 't': return (char) 0x09;
+ case 'n': return (char) 0x0a;
+ case 'r': return (char) 0x0d;
+ case 'Z': return (char) 0x1a;
+ case '\"': return (char) 0x22;
+ case '%': return (char) 0x25;
+ case '\'': return (char) 0x27;
+ case '\\': return (char) 0x5c;
+ case '_': return (char) 0x5f;
+ default: return second;
}
}
diff --git a/src/main/java/org/owasp/esapi/codecs/PercentCodec.java b/src/main/java/org/owasp/esapi/codecs/PercentCodec.java
index 5775055bb..f4c03dae7 100644
--- a/src/main/java/org/owasp/esapi/codecs/PercentCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/PercentCodec.java
@@ -54,7 +54,7 @@ public class PercentCodec extends AbstractCharacterCodec
* @return str encoded in UTF-8 as bytes.
* @throws IllegalStateException wrapped {@link
* UnsupportedEncodingException} if
- * {@link String.getBytes(String)} throws it.
+ * {@link String#getBytes(String)} throws it.
*/
private static byte[] toUtf8Bytes(String str)
{
diff --git a/src/main/java/org/owasp/esapi/codecs/PushBackSequenceImpl.java b/src/main/java/org/owasp/esapi/codecs/PushBackSequenceImpl.java
index 9f0c5223c..9c116cc2b 100644
--- a/src/main/java/org/owasp/esapi/codecs/PushBackSequenceImpl.java
+++ b/src/main/java/org/owasp/esapi/codecs/PushBackSequenceImpl.java
@@ -30,7 +30,7 @@ public Integer next() {
return save;
}
if ( input == null ) return null;
- if ( input.length() == 0 ) return null;
+ if ( input.isEmpty() ) return null;
if ( index >= input.length() ) return null;
final Integer point = input.codePointAt(index);
index += Character.charCount(point);
@@ -60,9 +60,9 @@ public Integer nextOctal() {
}
/**
- * Returns true if the parameter character is a hexidecimal digit 0 through 9, a through f, or A through F.
+ * Returns true if the parameter character is a hexadecimal digit 0 through 9, a through f, or A through F.
* @param c
- * @return true if it is a hexidecimal digit, false otherwise.
+ * @return true if it is a hexadecimal digit, false otherwise.
*/
public static boolean isHexDigit( Integer c ) {
if ( c == null ) return false;
@@ -88,7 +88,7 @@ public static boolean isOctalDigit( Integer c ) {
public Integer peek() {
if ( pushback != null ) return pushback;
if ( input == null ) return null;
- if ( input.length() == 0 ) return null;
+ if ( input.isEmpty() ) return null;
if ( index >= input.length() ) return null;
return input.codePointAt(index);
}
@@ -101,7 +101,7 @@ public Integer peek() {
public boolean peek( Integer c ) {
if ( pushback != null && pushback.intValue() == c ) return true;
if ( input == null ) return false;
- if ( input.length() == 0 ) return false;
+ if ( input.isEmpty() ) return false;
if ( index >= input.length() ) return false;
return input.codePointAt(index) == c;
}
diff --git a/src/main/java/org/owasp/esapi/codecs/PushbackString.java b/src/main/java/org/owasp/esapi/codecs/PushbackString.java
index b25cc1f20..c66996a56 100644
--- a/src/main/java/org/owasp/esapi/codecs/PushbackString.java
+++ b/src/main/java/org/owasp/esapi/codecs/PushbackString.java
@@ -59,7 +59,7 @@ public boolean hasNext() {
if (input == null){
return false;
}
- if (input.length() == 0){
+ if (input.isEmpty()){
return false;
}
if (index >= input.length()){
@@ -82,7 +82,7 @@ public Character next() {
if (input == null){
return null;
}
- if (input.length() == 0){
+ if (input.isEmpty()){
return null;
}
if (index >= input.length()){
@@ -124,11 +124,11 @@ public Character nextOctal() {
}
/**
- * Returns true if the parameter character is a hexidecimal digit 0 through
+ * Returns true if the parameter character is a hexadecimal digit 0 through
* 9, a through f, or A through F.
*
* @param c
- * @return true if it is a hexidecimal digit, false otherwise.
+ * @return true if it is a hexadecimal digit, false otherwise.
*/
public static boolean isHexDigit(Character c) {
if (c == null){
@@ -164,7 +164,7 @@ public Character peek() {
if (input == null){
return null;
}
- if (input.length() == 0){
+ if (input.isEmpty()){
return null;
}
if (index >= input.length()){
@@ -185,7 +185,7 @@ public boolean peek(Character c) {
if (input == null){
return false;
}
- if (input.length() == 0){
+ if (input.isEmpty()){
return false;
}
if (index >= input.length()){
diff --git a/src/main/java/org/owasp/esapi/codecs/Trie.java b/src/main/java/org/owasp/esapi/codecs/Trie.java
index fbb8c99ec..6f53e977f 100644
--- a/src/main/java/org/owasp/esapi/codecs/Trie.java
+++ b/src/main/java/org/owasp/esapi/codecs/Trie.java
@@ -9,11 +9,11 @@
public interface Trie extends Map
{
- public Map.Entry getLongestMatch(CharSequence key);
- public Map.Entry getLongestMatch(PushbackReader keyIn) throws IOException;
- public int getMaxKeyLength();
+ Map.Entry getLongestMatch(CharSequence key);
+ Map.Entry getLongestMatch(PushbackReader keyIn) throws IOException;
+ int getMaxKeyLength();
- static class TrieProxy implements Trie
+ class TrieProxy implements Trie
{
private Trie wrapped;
@@ -115,7 +115,7 @@ public int hashCode()
}
}
- static class Unmodifiable extends TrieProxy
+ class Unmodifiable extends TrieProxy
{
Unmodifiable(Trie toWrap)
{
@@ -158,7 +158,7 @@ public Set> entrySet()
}
}
- public static class Util
+ class Util
{
private Util()
{
diff --git a/src/main/java/org/owasp/esapi/codecs/XMLEntityCodec.java b/src/main/java/org/owasp/esapi/codecs/XMLEntityCodec.java
index c28734387..a171b0544 100644
--- a/src/main/java/org/owasp/esapi/codecs/XMLEntityCodec.java
+++ b/src/main/java/org/owasp/esapi/codecs/XMLEntityCodec.java
@@ -49,7 +49,7 @@ public class XMLEntityCodec extends AbstractCharacterCodec
private static final HashTrie entityToCharacterMap;
static
- { // populate entitites
+ { // populate entities
entityToCharacterMap = new HashTrie();
entityToCharacterMap.put("lt", '<');
entityToCharacterMap.put("gt", '>');
@@ -153,9 +153,9 @@ private static Character getNumericEntity(PushbackSequence input)
}
/**
- * Convert a integer code point to a Character.
+ * Convert an integer code point to a Character.
* @param i the integer
- * @return i as a Character or null if i is a invalid code point
+ * @return i as a Character or null if i is an invalid code point
* or outside of the Java char range.
*/
private static Character int2char(int i)
@@ -190,7 +190,7 @@ private static Character parseNumber(PushbackSequence input)
sb.append(c);
}
if(c==null)
- return null; // not ';' termintated
+ return null; // not ';' terminated
if(sb.length()<=0) // no digits
return null;
try
@@ -204,10 +204,10 @@ private static Character parseNumber(PushbackSequence input)
}
/**
- * Converts the rest of a hexidecimal numeric entity to a character.
+ * Converts the rest of a hexadecimal numeric entity to a character.
* @param input The input to read from. It is assumed that input
* is positioned at the character after the &#[xX]
- * @return The character decoded or null on failutre.
+ * @return The character decoded or null on failure.
*/
private static Character parseHex(PushbackSequence input)
{
@@ -247,7 +247,7 @@ private static Character parseHex(PushbackSequence input)
}
}
if(c==null)
- return null; // not ';' termintated
+ return null; // not ';' terminated
if(sb.length()<=0) // no digits
return null;
try
@@ -266,7 +266,7 @@ private static Character parseHex(PushbackSequence input)
* null if no decoding is possible.
* @param input The input to read from. It is assumed that input
* is positioned at the character after the &.
- * @return The character decoded or null on failutre.
+ * @return The character decoded or null on failure.
*/
private Character getNamedEntity(PushbackSequence input)
{
@@ -292,7 +292,7 @@ private Character getNamedEntity(PushbackSequence input)
input.next(); // read &
for(int i=0;i 0) {
+ while (!replacedContentList.isEmpty()) {
String origValue = replacedContentList.remove(0);
result = result.replaceFirst(replacementMarker, origValue);
}
@@ -89,7 +89,7 @@ public String restoreOriginalContent(String input) {
/**
* Allows the marker used as a replacement to be altered.
*
- * @param marker String replacment to use for regex matches.
+ * @param marker String replacement to use for regex matches.
*/
public void setReplacementMarker(String marker) {
if (!replacedContentList.isEmpty()) {
diff --git a/src/main/java/org/owasp/esapi/configuration/AbstractPrioritizedPropertyLoader.java b/src/main/java/org/owasp/esapi/configuration/AbstractPrioritizedPropertyLoader.java
index 8869694ce..debdc1174 100644
--- a/src/main/java/org/owasp/esapi/configuration/AbstractPrioritizedPropertyLoader.java
+++ b/src/main/java/org/owasp/esapi/configuration/AbstractPrioritizedPropertyLoader.java
@@ -7,7 +7,7 @@
import java.util.Properties;
/**
- * Abstrace class that supports two "levels" of priorities for ESAPI properties.
+ * Abstract class that supports two "levels" of priorities for ESAPI properties.
* The higher level is the property file supported by an "operations" team and
* the lower level is the property file intended to be supported by the
* "development" team. ESAPI properties defined in the lower level properties
@@ -42,7 +42,7 @@ public AbstractPrioritizedPropertyLoader(String filename, int priority) throws I
/**
* Get priority of this property loader. If two and more loaders can return value for the same property key,
- * the one with highest priority will be chosen.
+ * the one with the highest priority will be chosen.
* @return priority of this property loader
*/
public int priority() {
@@ -73,7 +73,7 @@ private void initProperties() throws IOException {
if ( file.canRead() ) {
loadPropertiesFromFile(file);
} else {
- throw new IOException("Can't read specificied configuration file: " + filename);
+ throw new IOException("Can't read specified configuration file: " + filename);
}
} else {
throw new FileNotFoundException("Specified configuration file " + filename + " does not exist or not regular file");
diff --git a/src/main/java/org/owasp/esapi/configuration/EsapiPropertyLoaderFactory.java b/src/main/java/org/owasp/esapi/configuration/EsapiPropertyLoaderFactory.java
index d6a1dffcd..49bd4766b 100644
--- a/src/main/java/org/owasp/esapi/configuration/EsapiPropertyLoaderFactory.java
+++ b/src/main/java/org/owasp/esapi/configuration/EsapiPropertyLoaderFactory.java
@@ -19,7 +19,7 @@ public class EsapiPropertyLoaderFactory {
public static AbstractPrioritizedPropertyLoader createPropertyLoader(EsapiConfiguration cfg)
throws ConfigurationException, IOException {
String cfgPath = System.getProperty(cfg.getConfigName());
- if ( cfgPath == null || cfgPath.equals("") ) {
+ if ( cfgPath == null || cfgPath.isEmpty() ) {
// TODO / FIXME:
// This case was previously a warning, but it should NOT have been
// since these system properties are optional. Most people just use
diff --git a/src/main/java/org/owasp/esapi/configuration/consts/EsapiConfiguration.java b/src/main/java/org/owasp/esapi/configuration/consts/EsapiConfiguration.java
index e5e330569..43df2fa1c 100644
--- a/src/main/java/org/owasp/esapi/configuration/consts/EsapiConfiguration.java
+++ b/src/main/java/org/owasp/esapi/configuration/consts/EsapiConfiguration.java
@@ -16,7 +16,7 @@ public enum EsapiConfiguration {
String configName;
/**
- * Priority of configuration (higher numer - higher priority).
+ * Priority of configuration (higher number - higher priority).
*/
int priority;
diff --git a/src/main/java/org/owasp/esapi/crypto/CipherText.java b/src/main/java/org/owasp/esapi/crypto/CipherText.java
index e0b549da3..58f5a8635 100644
--- a/src/main/java/org/owasp/esapi/crypto/CipherText.java
+++ b/src/main/java/org/owasp/esapi/crypto/CipherText.java
@@ -484,7 +484,7 @@ public boolean validateMAC(SecretKey authKey) {
return true;
} else {
// This *used* to be the case (for versions 2.0 and 2.0.1) where we tried to
- // accomodate the deprecated decrypt() method from ESAPI 1.4. Unfortunately,
+ // accommodate the deprecated decrypt() method from ESAPI 1.4. Unfortunately,
// that was an EPIC FAIL. (See Google Issue # 306 for details.)
logger.warning(Logger.SECURITY_FAILURE, "MAC may have been tampered with (e.g., length set to 0).");
return false; // Deprecated decrypt() method removed, so now return false.
@@ -494,7 +494,7 @@ public boolean validateMAC(SecretKey authKey) {
/**
* Return this {@code CipherText} object as a portable (i.e., network byte
* ordered) serialized byte array. Note this is not the same as
- * returning a serialized object using Java serialization. Instead this
+ * returning a serialized object using Java serialization. Instead, this
* is a representation that all ESAPI implementations will use to pass
* ciphertext between different programming language implementations.
*
@@ -539,7 +539,7 @@ public void setCiphertext(byte[] ciphertext)
{
if ( ! macComputed() ) {
if ( ciphertext == null || ciphertext.length == 0 ) {
- throw new EncryptionException("Encryption faled; no ciphertext",
+ throw new EncryptionException("Encryption failed; no ciphertext",
"Ciphertext may not be null or 0 length!");
}
if ( isCollected(CipherTextFlags.CIPHERTEXT) ) {
@@ -573,7 +573,7 @@ public void setIVandCiphertext(byte[] iv, byte[] ciphertext)
}
if ( ! macComputed() ) {
if ( ciphertext == null || ciphertext.length == 0 ) {
- throw new EncryptionException("Encryption faled; no ciphertext",
+ throw new EncryptionException("Encryption failed; no ciphertext",
"Ciphertext may not be null or 0 length!");
}
if ( iv == null || iv.length == 0 ) {
@@ -789,7 +789,7 @@ protected boolean canEqual(Object other) {
*
* HMAC-SHA1(nonce, IV + plaintext)
*
- * Note that only HMAC-SHA1 is used for the MAC calcuation. Unlike
+ * Note that only HMAC-SHA1 is used for the MAC calculation. Unlike
* the PRF used for derived key generation in the {@code KeyDerivationFunction}
* class, the user cannot change the algorithm used to compute the MAC itself.
* One reason for that is that we don't want the MAC value to be excessively
diff --git a/src/main/java/org/owasp/esapi/crypto/CipherTextSerializer.java b/src/main/java/org/owasp/esapi/crypto/CipherTextSerializer.java
index c5daa7d85..c8b0315b2 100644
--- a/src/main/java/org/owasp/esapi/crypto/CipherTextSerializer.java
+++ b/src/main/java/org/owasp/esapi/crypto/CipherTextSerializer.java
@@ -26,7 +26,7 @@
* and do not have extensive support for the various implementation languages which ESAPI
* supports. (Perhaps wishful thinking that other ESAPI implementations such as
* ESAPI for .NET, ESAPI for C, ESAPI for C++, etc. will all support a single, common
- * serialization technique so they could exchange encrypted data.)
+ * serialization technique, so they could exchange encrypted data.)
*
* @author kevin.w.wall@gmail.com
* @since 2.0
@@ -34,12 +34,12 @@
*/
public class CipherTextSerializer {
// This should be *same* version as in CipherText & KeyDerivationFunction as
- // these versions all need to work together. Therefore, when one changes one
- // one these versions, the other should be reviewed and changed as well to
+ // these versions all need to work together. Therefore, when someone changes one
+ // of these versions, the other should be reviewed and changed as well to
// accommodate any differences.
// Previous versions: 20110203 - Original version (ESAPI releases 2.0 & 2.0.1)
// 20130830 - Fix to issue #306 (release 2.1.0)
- // We check that in an static initialization block below.
+ // We check that in a static initialization block below.
public static final int cipherTextSerializerVersion = 20130830; // Current version. Format: YYYYMMDD, max is 99991231.
private static final long serialVersionUID = cipherTextSerializerVersion;
@@ -207,12 +207,12 @@ private byte[] computeSerialization(int kdfInfo, long timestamp,
// All strings are written as UTF-8 encoded byte streams with the
// length prepended before it as a short. The prepended length is
- // more for the benefit of languages like C so they can pre-allocate
+ // more for the benefit of languages like C, so they can pre-allocate
// char arrays without worrying about buffer overflows.
private void writeString(ByteArrayOutputStream baos, String str) {
byte[] bytes;
try {
- if ( str == null || str.length() == 0 ) {
+ if ( str == null || str.isEmpty() ) {
throw new IllegalArgumentException("Program error? writeString: str is null or empty!");
}
bytes = str.getBytes("UTF8");
@@ -405,7 +405,7 @@ private CipherText convertToCipherText(byte[] cipherTextSerializedBytes)
// Fixed in ESAPI crypto version 20130839. Previously is didn't really matter
// because there was only one version (20110203) and it defaulted to that
// version, which was the current version. But we don't want that as now there
- // are two versions and we could be decrypting data encrypted using the previous
+ // are two versions, and we could be decrypting data encrypted using the previous
// version.
ct.setKDF_PRF(kdfPrf);
ct.setKDFVersion(kdfVers);
diff --git a/src/main/java/org/owasp/esapi/crypto/CryptoHelper.java b/src/main/java/org/owasp/esapi/crypto/CryptoHelper.java
index 922fbf33d..018f3ff8d 100644
--- a/src/main/java/org/owasp/esapi/crypto/CryptoHelper.java
+++ b/src/main/java/org/owasp/esapi/crypto/CryptoHelper.java
@@ -50,13 +50,13 @@ public class CryptoHelper {
* @param keySize The key size, in bits.
* @return A random {@code SecretKey} is returned.
* @throws EncryptionException Thrown if cannot create secret key conforming to
- * requested algorithm with requested size. Typically this is caused by
+ * requested algorithm with requested size. Typically, this is caused by
* specifying an unavailable algorithm or invalid key size.
*/
public static SecretKey generateSecretKey(String alg, int keySize)
throws EncryptionException
{
- if ( alg == null || alg.equals("") ) {
+ if ( alg == null || alg.isEmpty() ) {
throw new IllegalArgumentException("Algorithm must not be null or empty."); // Avoid later possibly ambiguous NPE.
}
if ( keySize <= 0 ) {
@@ -128,7 +128,7 @@ public static SecretKey generateSecretKey(String alg, int keySize)
* be a common encoding supported by all Java implementations. Support
* for it is usually in rt.jar.) This exception is also thrown if the
* requested {@code keySize} parameter exceeds the length of the number of
- * bytes provded in the {@code keyDerivationKey} parameter.
+ * bytes provided in the {@code keyDerivationKey} parameter.
* @throws InvalidKeyException Likely indicates a coding error. Should not happen.
* @throws EncryptionException Throw for some precondition violations.
* @deprecated Use same method in {@code KeyDerivationFunction} instead. This method will be removed as of
@@ -189,7 +189,7 @@ public static boolean isCombinedCipherMode(String cipherMode)
if ( cipherMode == null ) {
throw new IllegalArgumentException("Cipher mode may not be null");
}
- if ( cipherMode.equals("") ) {
+ if ( cipherMode.isEmpty() ) {
throw new IllegalArgumentException("Cipher mode may not be empty string");
}
List combinedCipherModes =
@@ -254,7 +254,7 @@ public static boolean isMACRequired(CipherText ct) {
* should be embedded within the {@code CipherText} object by using a
* derived key based on the specified {@code SecretKey}.
*
- * @param sk The {@code SecretKey} used to derived a key to check
+ * @param sk The {@code SecretKey} used to derive a key to check
* the authenticity via the MAC.
* @param ct The {@code CipherText} that we are checking for a
* valid MAC.
@@ -266,21 +266,22 @@ public static boolean isMACRequired(CipherText ct) {
*/
public static boolean isCipherTextMACvalid(SecretKey sk, CipherText ct)
{
- if ( CryptoHelper.isMACRequired( ct ) ) {
- try {
- KeyDerivationFunction kdf = new KeyDerivationFunction( ct.getKDF_PRF() );
- SecretKey authKey = kdf.computeDerivedKey(sk, ct.getKeySize(), "authenticity");
- boolean validMAC = ct.validateMAC( authKey );
- return validMAC;
- } catch (Exception ex) {
- // Error on side of security. If this fails and can't verify MAC
- // assume it is invalid. Note that CipherText.toString() does not
- // print the actual ciphertext.
- logger.warning(Logger.SECURITY_FAILURE, "Unable to validate MAC for ciphertext " + ct, ex);
- return false;
- }
+ if (!CryptoHelper.isMACRequired(ct)) {
+ return true;
+ }
+
+ try {
+ KeyDerivationFunction kdf = new KeyDerivationFunction( ct.getKDF_PRF() );
+ SecretKey authKey = kdf.computeDerivedKey(sk, ct.getKeySize(), "authenticity");
+ boolean validMAC = ct.validateMAC( authKey );
+ return validMAC;
+ } catch (Exception ex) {
+ // Error on side of security. If this fails and can't verify MAC
+ // assume it is invalid. Note that CipherText.toString() does not
+ // print the actual ciphertext.
+ logger.warning(Logger.SECURITY_FAILURE, "Unable to validate MAC for ciphertext " + ct, ex);
+ return false;
}
- return true;
}
/**
diff --git a/src/main/java/org/owasp/esapi/crypto/CryptoToken.java b/src/main/java/org/owasp/esapi/crypto/CryptoToken.java
index c12ee10dc..0dce89e94 100644
--- a/src/main/java/org/owasp/esapi/crypto/CryptoToken.java
+++ b/src/main/java/org/owasp/esapi/crypto/CryptoToken.java
@@ -68,10 +68,10 @@
*
* The attribute value may contain any value. However, values containing
* either '=' or ';' will be quoted using '\'. Likewise, values containing '\'
- * will also be quoted using '\'. Hence if original name/value pair were
+ * will also be quoted using '\'. Hence, if original name/value pair were
* name=ab=xy\; * this would be represented as name=ab\=xy\\\;.
* To ensure things are "safe" (from a security perspective), attribute
- * names must conform the the Java regular expression
+ * names must conform to the Java regular expression
*
* [A-Za-z0-9_\.-]+
*
@@ -385,7 +385,6 @@ public void addAttributes(final Map attrs) throws ValidationExce
String value = entry.getValue();
setAttribute(key, value);
}
- return;
}
/**
@@ -409,7 +408,7 @@ public String getAttribute(String name) {
*/
@SuppressWarnings("unchecked")
public Map getAttributes() {
- // Unfortunately, this requires a cast, which requires us to supress warnings.
+ // Unfortunately, this requires a cast, which requires us to suppress warnings.
return (Map) attributes.clone();
}
@@ -567,7 +566,7 @@ private String getQuotedAttributes() {
// Do NOT define a toString() method as there may be sensitive
// information contained in the attribute names. If we absolutely
// need this, then only return the username and expiration time, and
- // _maybe_ the attribute names, but not there values. And obviously,
+ // _maybe_ the attribute names, but not their values. And obviously,
// we NEVER want to include the SecretKey should we decide to do this.
/*
* public String toString() { return null; }
@@ -724,7 +723,6 @@ private void decryptToken(SecretKey skey, String b64token) throws EncryptionExce
}
attributes.put(name, value);
}
- return;
}
private SecretKey getDefaultSecretKey(String encryptAlgorithm) {
diff --git a/src/main/java/org/owasp/esapi/crypto/KeyDerivationFunction.java b/src/main/java/org/owasp/esapi/crypto/KeyDerivationFunction.java
index 02f925bfb..0a94c105c 100644
--- a/src/main/java/org/owasp/esapi/crypto/KeyDerivationFunction.java
+++ b/src/main/java/org/owasp/esapi/crypto/KeyDerivationFunction.java
@@ -319,7 +319,7 @@ public SecretKey computeDerivedKey(SecretKey keyDerivationKey, int keySize, Stri
throw new IllegalArgumentException("Key size (" + keySize +
") must be a even multiple of 8-bits.");
}
- if ( purpose == null || "".equals(purpose) ) {
+ if ( purpose == null || purpose.isEmpty() ) {
throw new IllegalArgumentException("Purpose may not be null or empty.");
}
@@ -440,8 +440,8 @@ public SecretKey computeDerivedKey(SecretKey keyDerivationKey, int keySize, Stri
// not do this if tmpKey were declared in the do-while loop.
// Of course, in reality, trying to stomp these bits out is probably not
// realistic because the JIT is likely toing to be smart enough to
- // optimze this loop away. We probably could try to outsmart it, by
- // (say) writing out the overwritten bits to /dev/null, but then even
+ // optimize this loop away. We probably could try to outsmart it, by
+ // (say) writing out the overwritten bits to /dev/null, but even
// then we'd still probably have to overwrite with random bits rather
// than all null chars. How much is enough? Who knows? But it does point
// to a serious limitation in Java and many other languages that one
diff --git a/src/main/java/org/owasp/esapi/crypto/PlainText.java b/src/main/java/org/owasp/esapi/crypto/PlainText.java
index 60fda894c..4866b8048 100644
--- a/src/main/java/org/owasp/esapi/crypto/PlainText.java
+++ b/src/main/java/org/owasp/esapi/crypto/PlainText.java
@@ -16,7 +16,7 @@
* an {@code UnsupportedEncodingException}. However, UTF-8 encoding
* should be a standard encoding for all Java installations, so an
* {@code UnsupportedEncodingException} never actually be thrown. Therefore,
- * in order to to keep client code uncluttered, any possible
+ * in order to keep client code uncluttered, any possible
* {@code UnsupportedEncodingException}s will be first logged, and then
* re-thrown as a {@code RuntimeException} with the original
* {@code UnsupportedEncodingException} as the cause.
diff --git a/src/main/java/org/owasp/esapi/crypto/SecurityProviderLoader.java b/src/main/java/org/owasp/esapi/crypto/SecurityProviderLoader.java
index a5cbd708c..dcfa5490c 100644
--- a/src/main/java/org/owasp/esapi/crypto/SecurityProviderLoader.java
+++ b/src/main/java/org/owasp/esapi/crypto/SecurityProviderLoader.java
@@ -33,7 +33,7 @@ public class SecurityProviderLoader {
// Load the table with known providers. We load the (short) JCE name
// and the corresponding provider class. We don't 'new' the actual
// class name here because that would mean we would have to have all
- // these jars. Instead we use reflection and do it dynamically only
+ // these jars. Instead, we use reflection and do it dynamically only
// when SecurityProviderLoader.insertProviderAt() is called because
// presumably they will have the jar in their classpath for the
// provider they wish to use.
diff --git a/src/main/java/org/owasp/esapi/filters/RequestRateThrottleFilter.java b/src/main/java/org/owasp/esapi/filters/RequestRateThrottleFilter.java
index ed263e55e..47774b895 100644
--- a/src/main/java/org/owasp/esapi/filters/RequestRateThrottleFilter.java
+++ b/src/main/java/org/owasp/esapi/filters/RequestRateThrottleFilter.java
@@ -62,7 +62,7 @@ public void init(FilterConfig filterConfig)
* Checks to see if the current session has exceeded the allowed number
* of requests in the specified time period. If the threshold has been
* exceeded, then a short error message is written to the output stream and
- * no further processing is done on the request. Otherwise the request is
+ * no further processing is done on the request. Otherwise, the request is
* processed as normal.
* @param request
* @param response
diff --git a/src/main/java/org/owasp/esapi/filters/SecurityWrapperRequest.java b/src/main/java/org/owasp/esapi/filters/SecurityWrapperRequest.java
index 26fa7a7a3..71c74c652 100644
--- a/src/main/java/org/owasp/esapi/filters/SecurityWrapperRequest.java
+++ b/src/main/java/org/owasp/esapi/filters/SecurityWrapperRequest.java
@@ -628,7 +628,7 @@ public String getRequestURI() {
/**
* Returns the URL from the HttpServletRequest after canonicalizing and
* filtering out any dangerous characters.
- * @return The currect request URL
+ * @return The current request URL
*/
public StringBuffer getRequestURL() {
String url = getHttpServletRequest().getRequestURL().toString();
diff --git a/src/main/java/org/owasp/esapi/filters/SecurityWrapperResponse.java b/src/main/java/org/owasp/esapi/filters/SecurityWrapperResponse.java
index f05682cba..1676829a1 100644
--- a/src/main/java/org/owasp/esapi/filters/SecurityWrapperResponse.java
+++ b/src/main/java/org/owasp/esapi/filters/SecurityWrapperResponse.java
@@ -92,7 +92,7 @@ public void addCookie(Cookie cookie) {
String cookieValue = ESAPI.validator().getValidInput("cookie value", value, "HTTPCookieValue", sc.getIntProp("HttpUtilities.MaxHeaderValueSize"), false, errors);
// if there are no errors, then just set a cookie header
- if (errors.size() == 0) {
+ if (errors.isEmpty()) {
String header = createCookieHeader(name, value, maxAge, domain, path, secure);
this.addHeader("Set-Cookie", header);
return;
@@ -127,23 +127,24 @@ private String createCookieHeader(String name, String value, int maxAge, String
// create the special cookie header instead of creating a Java cookie
// Set-Cookie:=[; =][; expires=][;
// domain=][; path=][; secure][;HttpOnly
- String header = name + "=" + value;
+ StringBuilder header = new StringBuilder()
+ .append(name).append("=").append(value);
if (maxAge >= 0) {
- header += "; Max-Age=" + maxAge;
+ header.append("; Max-Age=").append(maxAge);
}
if (domain != null) {
- header += "; Domain=" + domain;
+ header.append("; Domain=").append(domain);
}
if (path != null) {
- header += "; Path=" + path;
+ header.append("; Path=").append(path);
}
if ( secure || ESAPI.securityConfiguration().getBooleanProp("HttpUtilities.ForceSecureCookies") ) {
- header += "; Secure";
+ header.append("; Secure");
}
if ( ESAPI.securityConfiguration().getBooleanProp("HttpUtilities.ForceHttpOnlyCookies") ) {
- header += "; HttpOnly";
+ header.append("; HttpOnly");
}
- return header;
+ return header.toString();
}
/**
diff --git a/src/main/java/org/owasp/esapi/logging/cleaning/CompositeLogScrubber.java b/src/main/java/org/owasp/esapi/logging/cleaning/CompositeLogScrubber.java
index 1638ca51f..72da7f2ba 100644
--- a/src/main/java/org/owasp/esapi/logging/cleaning/CompositeLogScrubber.java
+++ b/src/main/java/org/owasp/esapi/logging/cleaning/CompositeLogScrubber.java
@@ -21,7 +21,7 @@
* LogScrubber implementation which performs iterative delegate to an ordered
* List of LogScrubbers.
* The results of the delegate list of LogScrubbers is additive, meaning that
- * the the original message is passed to the first delegate and its return value
+ * the original message is passed to the first delegate and its return value
* is passed to the second (etc).
*
*/
diff --git a/src/main/java/org/owasp/esapi/logging/java/JavaLogBridge.java b/src/main/java/org/owasp/esapi/logging/java/JavaLogBridge.java
index 078afdf9b..2d1243c05 100644
--- a/src/main/java/org/owasp/esapi/logging/java/JavaLogBridge.java
+++ b/src/main/java/org/owasp/esapi/logging/java/JavaLogBridge.java
@@ -19,7 +19,7 @@
import org.owasp.esapi.Logger.EventType;
/**
- * Contract for translating an ESAPI log event into an Java log event.
+ * Contract for translating an ESAPI log event into a Java log event.
*
*/
public interface JavaLogBridge {
diff --git a/src/main/java/org/owasp/esapi/reference/AbstractAccessReferenceMap.java b/src/main/java/org/owasp/esapi/reference/AbstractAccessReferenceMap.java
index 242ff3e47..c17109913 100644
--- a/src/main/java/org/owasp/esapi/reference/AbstractAccessReferenceMap.java
+++ b/src/main/java/org/owasp/esapi/reference/AbstractAccessReferenceMap.java
@@ -90,9 +90,9 @@ public AbstractAccessReferenceMap( int initialSize ) {
* the direct references
* @deprecated This constructor internally calls the abstract method
* {@link #getUniqueReference()}. Since this is a constructor, any
- * subclass that implements getUniqueReference() has not had it's
+ * subclass that implements getUniqueReference() has not had its
* own constructor run. This leads to strange bugs because subclass
- * internal state is initializaed after calls to getUniqueReference()
+ * internal state is initialized after calls to getUniqueReference()
* have already happened. If this constructor is desired in a
* subclass, consider running {@link #update(Set)} in the subclass
* constructor instead.
@@ -108,7 +108,7 @@ public AbstractAccessReferenceMap( Set