1
0
mirror of synced 2026-05-22 21:33:16 +00:00

SEC-1689: Re-instate crypto as separate library (for use in non-Spring Security apps), as well as packaging with core.

This commit is contained in:
Luke Taylor
2011-06-10 00:01:25 +01:00
parent ecfffaaa3f
commit e27f655e9d
31 changed files with 48 additions and 11 deletions
+18 -8
View File
@@ -1,5 +1,9 @@
// Core build file
// We don't define a module dependency on crypto to avoid creating a transitive dependency
def cryptoProject = project(':spring-security-crypto')
def cryptoClasses = cryptoProject.sourceSets.main.classes
dependencies {
compile 'aopalliance:aopalliance:1.0',
"net.sf.ehcache:ehcache:$ehcacheVersion",
@@ -20,16 +24,22 @@ dependencies {
"cglib:cglib-nodep:$cglibVersion"
}
// jdkVersion = System.properties['java.version']
// isJdk6 = jdkVersion >= '1.6'
int maxAESKeySize = javax.crypto.Cipher.getMaxAllowedKeyLength('AES')
compileJava.dependsOn cryptoProject.compileJava
classes.dependsOn cryptoProject.classes
classes.doLast {
copy {
from cryptoClasses
into sourceSets.main.classesDir
}
}
sourceSets.main.compileClasspath += cryptoClasses
sourceSets.test.compileClasspath += cryptoClasses
sourceJar.from cryptoProject.sourceSets.main.java
test {
systemProperties['springSecurityVersion'] = version
systemProperties['springVersion'] = springVersion
if (maxAESKeySize < 256) {
logger.warn("AES keysize limited to $maxAESKeySize, skipping EncryptorsTests")
exclude '**/EncryptorsTests.class'
}
}
@@ -1,642 +0,0 @@
package org.springframework.security.crypto.codec;
/**
* Base64 encoder which is a reduced version of Robert Harder's public domain implementation (version 2.3.7).
* See <a href="http://iharder.net/base64">http://iharder.net/base64</a> for more information.
* <p>
* For internal use only.
*
* @author Luke Taylor
* @since 3.0
*/
public final class Base64 {
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding in first bit. Value is one. */
public final static int ENCODE = 1;
/** Specify decoding in first bit. Value is zero. */
public final static int DECODE = 0;
/** Do break lines when encoding. Value is 8. */
public final static int DO_BREAK_LINES = 8;
/**
* Encode using Base64-like encoding that is URL- and Filename-safe as described
* in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* It is important to note that data encoded this way is <em>not</em> officially valid Base64,
* or at the very least should not be called Base64 without also specifying that is
* was encoded using the URL- and Filename-safe dialect.
*/
public final static int URL_SAFE = 16;
/**
* Encode using the special "ordered" dialect of Base64 described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
public final static int ORDERED = 32;
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */
/** The 64 valid Base64 values. */
/* Host platform me be something funny like EBCDIC, so we hardcode these values. */
private final static byte[] _STANDARD_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] _STANDARD_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */
/**
* Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548:
* <a href="http://www.faqs.org/rfcs/rfc3548.html">http://www.faqs.org/rfcs/rfc3548.html</a>.
* Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash."
*/
private final static byte[] _URL_SAFE_ALPHABET = {
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_'
};
/**
* Used in decoding URL- and Filename-safe dialects of Base64.
*/
private final static byte[] _URL_SAFE_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
62, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
63, // Underscore at decimal 95
-9, // Decimal 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */
/**
* I don't get the point of this technique, but someone requested it,
* and it is described here:
* <a href="http://www.faqs.org/qa/rfcc-1940.html">http://www.faqs.org/qa/rfcc-1940.html</a>.
*/
private final static byte[] _ORDERED_ALPHABET = {
(byte)'-',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4',
(byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9',
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'_',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z'
};
/**
* Used in decoding the "ordered" dialect of Base64.
*/
private final static byte[] _ORDERED_DECODABET = {
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
-9, // Plus sign at decimal 43
-9, // Decimal 44
0, // Minus sign at decimal 45
-9, // Decimal 46
-9, // Slash at decimal 47
1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M'
24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z'
-9,-9,-9,-9, // Decimal 91 - 94
37, // Underscore at decimal 95
-9, // Decimal 96
38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm'
51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z'
-9,-9,-9,-9,-9 // Decimal 123 - 127
,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255
};
public static byte[] decode(byte[] bytes) {
return decode(bytes, 0, bytes.length, NO_OPTIONS);
}
public static byte[] encode(byte[] bytes) {
return encodeBytesToBytes(bytes, 0, bytes.length, NO_OPTIONS);
}
public static boolean isBase64(byte[] bytes) {
try {
decode(bytes);
} catch (InvalidBase64CharacterException e) {
return false;
}
return true;
}
/**
* Returns one of the _SOMETHING_ALPHABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED <b>and</b> URLSAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private static byte[] getAlphabet( int options ) {
if ((options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_ALPHABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_ALPHABET;
} else {
return _STANDARD_ALPHABET;
}
}
/**
* Returns one of the _SOMETHING_DECODABET byte arrays depending on
* the options specified.
* It's possible, though silly, to specify ORDERED and URL_SAFE
* in which case one of them will be picked, though there is
* no guarantee as to which one will be picked.
*/
private static byte[] getDecodabet( int options ) {
if( (options & URL_SAFE) == URL_SAFE) {
return _URL_SAFE_DECODABET;
} else if ((options & ORDERED) == ORDERED) {
return _ORDERED_DECODABET;
} else {
return _STANDARD_DECODABET;
}
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* <p>Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.</p>
* <p>This is the lowest level of the encoding methods with
* all possible parameters.</p>
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset, int options ) {
byte[] ALPHABET = getAlphabet( options );
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
}
}
/**
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @return The Base64-encoded data as a String
* @see Base64#DO_BREAK_LINES
* @throws java.io.IOException if there is an error
* @throws NullPointerException if source array is null
* @throws IllegalArgumentException if source array, offset, or length are invalid
* @since 2.3.1
*/
private static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) {
if( source == null ){
throw new NullPointerException( "Cannot serialize a null array." );
} // end if: null
if( off < 0 ){
throw new IllegalArgumentException( "Cannot have negative offset: " + off );
} // end if: off < 0
if( len < 0 ){
throw new IllegalArgumentException( "Cannot have length offset: " + len );
} // end if: len < 0
if( off + len > source.length ){
throw new IllegalArgumentException(
String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length));
} // end if: off < 0
boolean breakLines = (options & DO_BREAK_LINES) > 0;
//int len43 = len * 4 / 3;
//byte[] outBuff = new byte[ ( len43 ) // Main 4:3
// + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
// + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
// Try to determine more precisely how big the array needs to be.
// If we get it right, we don't have to do an array copy, and
// we save a bunch of memory.
int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding
if( breakLines ){
encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters
}
byte[] outBuff = new byte[ encLen ];
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 ) {
encode3to4( source, d+off, 3, outBuff, e, options );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len ) {
encode3to4( source, d+off, len - d, outBuff, e, options );
e += 4;
} // end if: some padding needed
// Only resize array if we didn't guess it right.
if( e <= outBuff.length - 1 ){
byte[] finalOut = new byte[e];
System.arraycopy(outBuff,0, finalOut,0,e);
//System.err.println("Having to resize array from " + outBuff.length + " to " + e );
return finalOut;
} else {
//System.err.println("No need to resize array.");
return outBuff;
}
}
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
* <p>This is the lowest level of the decoding methods with
* all possible parameters.</p>
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
* @return the number of decoded bytes converted
* @throws NullPointerException if source or destination arrays are null
* @throws IllegalArgumentException if srcOffset or destOffset are invalid
* or there is not enough room in the array.
* @since 1.3
*/
private static int decode4to3(
byte[] source, int srcOffset,
byte[] destination, int destOffset, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Source array was null." );
} // end if
if( destination == null ){
throw new NullPointerException( "Destination array was null." );
} // end if
if( srcOffset < 0 || srcOffset + 3 >= source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) );
} // end if
if( destOffset < 0 || destOffset +2 >= destination.length ){
throw new IllegalArgumentException( String.format(
"Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) );
} // end if
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else {
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}
}
/**
* Low-level access to decoding ASCII characters in
* the form of a byte array. <strong>Ignores GUNZIP option, if
* it's set.</strong> This is not generally a recommended method,
* although it is used internally as part of the decoding process.
* Special case: if len = 0, an empty array is returned. Still,
* if you need more speed and reduced memory footprint (and aren't
* gzipping), consider this method.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @param options Can specify options such as alphabet type to use
* @return decoded data
* @throws IllegalArgumentException If bogus characters exist in source data
*/
private static byte[] decode( byte[] source, int off, int len, int options ) {
// Lots of error checking and exception throwing
if( source == null ){
throw new NullPointerException( "Cannot decode null source array." );
} // end if
if( off < 0 || off + len > source.length ){
throw new IllegalArgumentException( String.format(
"Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) );
} // end if
if( len == 0 ){
return new byte[0];
}else if( len < 4 ){
throw new IllegalArgumentException(
"Base64-encoded string must have at least four characters, but length specified was " + len );
} // end if
byte[] DECODABET = getDecodabet( options );
int len34 = len * 3 / 4; // Estimate on array size
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0; // Keep track of where we're writing
byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space
int b4Posn = 0; // Keep track of four byte input buffer
int i = 0; // Source array counter
byte sbiDecode = 0; // Special value from DECODABET
for(i = off; i < off+len; i++ ) { // Loop through source
sbiDecode = DECODABET[ source[i]&0xFF ];
// White space, Equals sign, or legit Base64 character
// Note the values such as -5 and -9 in the
// DECODABETs at the top of the file.
if( sbiDecode >= WHITE_SPACE_ENC ) {
if( sbiDecode >= EQUALS_SIGN_ENC ) {
b4[ b4Posn++ ] = source[i]; // Save non-whitespace
if( b4Posn > 3 ) { // Time to decode?
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( source[i] == EQUALS_SIGN ) {
break;
}
}
}
}
else {
// There's a bad input character in the Base64 stream.
throw new InvalidBase64CharacterException( String.format(
"Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) );
}
}
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
}
}
class InvalidBase64CharacterException extends IllegalArgumentException {
InvalidBase64CharacterException(String message) {
super(message);
}
}
@@ -1,54 +0,0 @@
package org.springframework.security.crypto.codec;
/**
* Hex data encoder. Converts byte arrays (such as those obtained from message digests)
* into hexadecimal string representation.
* <p>
* For internal use only.
*
* @author Luke Taylor
* @since 3.0
*/
public final class Hex {
private static final char[] HEX = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
public static char[] encode(byte[] bytes) {
final int nBytes = bytes.length;
char[] result = new char[2*nBytes];
int j = 0;
for (int i=0; i < nBytes; i++) {
// Char for top 4 bits
result[j++] = HEX[(0xF0 & bytes[i]) >>> 4 ];
// Bottom 4
result[j++] = HEX[(0x0F & bytes[i])];
}
return result;
}
public static byte[] decode(CharSequence s) {
int nChars = s.length();
if (nChars % 2 != 0) {
throw new IllegalArgumentException("Hex-encoded string must have an even number of characters");
}
byte[] result = new byte[nChars / 2];
for (int i = 0; i < nChars; i += 2) {
int msb = Character.digit(s.charAt(i), 16);
int lsb = Character.digit(s.charAt(i+1), 16);
if (msb < 0 || lsb < 0) {
throw new IllegalArgumentException("Non-hex character in input: " + s);
}
result[i / 2] = (byte) ((msb << 4) | lsb);
}
return result;
}
}
@@ -1,42 +0,0 @@
package org.springframework.security.crypto.codec;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.*;
/**
* UTF-8 Charset encoder/decoder.
* <p>
* For internal use only.
*
* @author Luke Taylor
*/
public final class Utf8 {
private static final Charset CHARSET = Charset.forName("UTF-8");
/**
* Get the bytes of the String in UTF-8 encoded form.
*/
public static byte[] encode(CharSequence string) {
try {
ByteBuffer bytes = CHARSET.newEncoder().encode(CharBuffer.wrap(string));
return Arrays.copyOfRange(bytes.array(), 0, bytes.limit());
} catch (CharacterCodingException e) {
throw new IllegalArgumentException("Encoding failed", e);
}
}
/**
* Decode the bytes in UTF-8 form into a String.
*/
public static String decode(byte[] bytes) {
try {
return CHARSET.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new IllegalArgumentException("Decoding failed", e);
}
}
}
@@ -1,4 +0,0 @@
/**
* Internal codec classes. Only intended for use within the framework.
*/
package org.springframework.security.crypto.codec;
@@ -1,104 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
import static org.springframework.security.crypto.encrypt.CipherUtils.doFinal;
import static org.springframework.security.crypto.encrypt.CipherUtils.initCipher;
import static org.springframework.security.crypto.encrypt.CipherUtils.newCipher;
import static org.springframework.security.crypto.encrypt.CipherUtils.newSecretKey;
import static org.springframework.security.crypto.util.EncodingUtils.concatenate;
import static org.springframework.security.crypto.util.EncodingUtils.subArray;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
/**
* Encryptor that uses 256-bit AES encryption.
*
* @author Keith Donald
*/
final class AesBytesEncryptor implements BytesEncryptor {
private final SecretKey secretKey;
private final Cipher encryptor;
private final Cipher decryptor;
private final BytesKeyGenerator ivGenerator;
public AesBytesEncryptor(String password, CharSequence salt) {
this(password, salt, null);
}
public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator) {
PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256);
SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec);
this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES");
encryptor = newCipher(AES_ALGORITHM);
decryptor = newCipher(AES_ALGORITHM);
this.ivGenerator = ivGenerator != null ? ivGenerator : NULL_IV_GENERATOR;
}
public byte[] encrypt(byte[] bytes) {
synchronized (encryptor) {
byte[] iv = ivGenerator.generateKey();
initCipher(encryptor, Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
byte[] encrypted = doFinal(encryptor, bytes);
return ivGenerator != NULL_IV_GENERATOR ? concatenate(iv, encrypted) : encrypted;
}
}
public byte[] decrypt(byte[] encryptedBytes) {
synchronized (decryptor) {
byte[] iv = iv(encryptedBytes);
initCipher(decryptor, Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
return doFinal(decryptor, ivGenerator != NULL_IV_GENERATOR ? encrypted(encryptedBytes, iv.length) : encryptedBytes);
}
}
// internal helpers
private byte[] iv(byte[] encrypted) {
return ivGenerator != NULL_IV_GENERATOR ? subArray(encrypted, 0, ivGenerator.getKeyLength()) : NULL_IV_GENERATOR.generateKey();
}
private byte[] encrypted(byte[] encryptedBytes, int ivLength) {
return subArray(encryptedBytes, ivLength, encryptedBytes.length);
}
private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final BytesKeyGenerator NULL_IV_GENERATOR = new BytesKeyGenerator() {
private final byte[] VALUE = new byte[16];
public int getKeyLength() {
return VALUE.length;
}
public byte[] generateKey() {
return VALUE;
}
};
}
@@ -1,34 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
/**
* Service interface for symmetric data encryption.
* @author Keith Donald
*/
public interface BytesEncryptor {
/**
* Encrypt the byte array.
*/
byte[] encrypt(byte[] byteArray);
/**
* Decrypt the byte array.
*/
byte[] decrypt(byte[] encryptedByteArray);
}
@@ -1,132 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
/**
* Static helper for working with the Cipher API.
* @author Keith Donald
*/
class CipherUtils {
/**
* Generates a SecretKey.
*/
public static SecretKey newSecretKey(String algorithm, String password) {
return newSecretKey(algorithm, new PBEKeySpec(password.toCharArray()));
}
/**
* Generates a SecretKey.
*/
public static SecretKey newSecretKey(String algorithm, PBEKeySpec keySpec) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
return factory.generateSecret(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Not a valid encryption algorithm", e);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Not a valid secret key", e);
}
}
/**
* Constructs a new Cipher.
*/
public static Cipher newCipher(String algorithm) {
try {
return Cipher.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException("Not a valid encryption algorithm", e);
} catch (NoSuchPaddingException e) {
throw new IllegalStateException("Should not happen", e);
}
}
/**
* Initializes the Cipher for use.
*/
public static <T extends AlgorithmParameterSpec> T getParameterSpec(Cipher cipher, Class<T> parameterSpecClass) {
try {
return cipher.getParameters().getParameterSpec(parameterSpecClass);
} catch (InvalidParameterSpecException e) {
throw new IllegalArgumentException("Unable to access parameter", e);
}
}
/**
* Initializes the Cipher for use.
*/
public static void initCipher(Cipher cipher, int mode, SecretKey secretKey) {
initCipher(cipher, mode, secretKey, null);
}
/**
* Initializes the Cipher for use.
*/
public static void initCipher(Cipher cipher, int mode, SecretKey secretKey, byte[] salt, int iterationCount) {
initCipher(cipher, mode, secretKey, new PBEParameterSpec(salt, iterationCount));
}
/**
* Initializes the Cipher for use.
*/
public static void initCipher(Cipher cipher, int mode, SecretKey secretKey, AlgorithmParameterSpec parameterSpec) {
try {
if (parameterSpec != null) {
cipher.init(mode, secretKey, parameterSpec);
} else {
cipher.init(mode, secretKey);
}
} catch (InvalidKeyException e) {
throw new IllegalArgumentException("Unable to initialize due to invalid secret key", e);
} catch (InvalidAlgorithmParameterException e) {
throw new IllegalStateException("Unable to initialize due to invalid decryption parameter spec", e);
}
}
/**
* Invokes the Cipher to perform encryption or decryption (depending on the initialized mode).
*/
public static byte[] doFinal(Cipher cipher, byte[] input) {
try {
return cipher.doFinal(input);
} catch (IllegalBlockSizeException e) {
throw new IllegalStateException("Unable to invoke Cipher due to illegal block size", e);
} catch (BadPaddingException e) {
throw new IllegalStateException("Unable to invoke Cipher due to bad padding", e);
}
}
private CipherUtils() {
}
}
@@ -1,91 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
import org.springframework.security.crypto.keygen.KeyGenerators;
/**
* Factory for commonly used encryptors.
* Defines the public API for constructing {@link BytesEncryptor} and {@link TextEncryptor} implementations.
*
* @author Keith Donald
*/
public class Encryptors {
/**
* Creates a standard password-based bytes encryptor using 256 bit AES encryption.
* Derives the secret key using PKCS #5's PBKDF2 (Password-Based Key Derivation Function #2).
* Salts the password to prevent dictionary attacks against the key.
* The provided salt is expected to be hex-encoded; it should be random and at least 8 bytes in length.
* Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique.
* Requires Java 6.
*
* @param password the password used to generate the encryptor's secret key; should not be shared
* @param salt a hex-encoded, random, site-global salt value to use to generate the key
*/
public static BytesEncryptor standard(CharSequence password, CharSequence salt) {
return new AesBytesEncryptor(password.toString(), salt, KeyGenerators.secureRandom(16));
}
/**
* Creates a text encryptor that uses standard password-based encryption.
* Encrypted text is hex-encoded.
*
* @param password the password used to generate the encryptor's secret key; should not be shared
*/
public static TextEncryptor text(CharSequence password, CharSequence salt) {
return new HexEncodingTextEncryptor(standard(password, salt));
}
/**
* Creates an encryptor for queryable text strings that uses standard password-based encryption.
* Uses a 16-byte all-zero initialization vector so encrypting the same data results in the same encryption result.
* This is done to allow encrypted data to be queried against.
* Encrypted text is hex-encoded.
*
* @param password the password used to generate the encryptor's secret key; should not be shared
* @param salt a hex-encoded, random, site-global salt value to use to generate the secret key
*/
public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {
return new HexEncodingTextEncryptor(new AesBytesEncryptor(password.toString(), salt));
}
/**
* Creates a text encryptor that performs no encryption.
* Useful for developer testing environments where working with plain text strings is desired for simplicity.
*/
public static TextEncryptor noOpText() {
return NO_OP_TEXT_INSTANCE;
}
private Encryptors() {
}
private static final TextEncryptor NO_OP_TEXT_INSTANCE = new NoOpTextEncryptor();
private static final class NoOpTextEncryptor implements TextEncryptor {
public String encrypt(String text) {
return text;
}
public String decrypt(String encryptedText) {
return encryptedText;
}
}
}
@@ -1,43 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.codec.Utf8;
/**
* Delegates to an {@link BytesEncryptor} to encrypt text strings.
* Raw text strings are UTF-8 encoded before being passed to the encryptor.
* Encrypted strings are returned hex-encoded.
* @author Keith Donald
*/
final class HexEncodingTextEncryptor implements TextEncryptor {
private final BytesEncryptor encryptor;
public HexEncodingTextEncryptor(BytesEncryptor encryptor) {
this.encryptor = encryptor;
}
public String encrypt(String text) {
return new String(Hex.encode(encryptor.encrypt(Utf8.encode(text))));
}
public String decrypt(String encryptedText) {
return Utf8.decode(encryptor.decrypt(Hex.decode(encryptedText)));
}
}
@@ -1,35 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.encrypt;
/**
* Service interface for symmetric encryption of text strings.
*
* @author Keith Donald
*/
public interface TextEncryptor {
/**
* Encrypt the raw text string.
*/
String encrypt(String text);
/**
* Decrypt the encrypted text string.
*/
String decrypt(String encryptedText);
}
@@ -1,35 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
/**
* A generator for unique byte array-based keys.
* @author Keith Donald
*/
public interface BytesKeyGenerator {
/**
* Get the length, in bytes, of keys created by this generator.
* Most unique keys are at least 8 bytes in length.
*/
int getKeyLength();
/**
* Generate a new key.
*/
byte[] generateKey();
}
@@ -1,37 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
import org.springframework.security.crypto.codec.Hex;
/**
* A StringKeyGenerator that generates hex-encoded String keys.
* Delegates to a {@link BytesKeyGenerator} for the actual key generation.
* @author Keith Donald
*/
final class HexEncodingStringKeyGenerator implements StringKeyGenerator {
private final BytesKeyGenerator keyGenerator;
public HexEncodingStringKeyGenerator(BytesKeyGenerator keyGenerator) {
this.keyGenerator = keyGenerator;
}
public String generateKey() {
return new String(Hex.encode(keyGenerator.generateKey()));
}
}
@@ -1,62 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
import java.security.SecureRandom;
/**
* Factory for commonly used key generators.
* Public API for constructing a {@link BytesKeyGenerator} or {@link StringKeyGenerator}.
* @author Keith Donald
*/
public class KeyGenerators {
/**
* Create a {@link BytesKeyGenerator} that uses a {@link SecureRandom} to generate keys of 8 bytes in length.
*/
public static BytesKeyGenerator secureRandom() {
return new SecureRandomBytesKeyGenerator();
}
/**
* Create a {@link BytesKeyGenerator} that uses a {@link SecureRandom} to generate keys of a custom length.
* @param keyLength the key length in bytes, e.g. 16, for a 16 byte key.
*/
public static BytesKeyGenerator secureRandom(int keyLength) {
return new SecureRandomBytesKeyGenerator(keyLength);
}
/**
* Create a {@link BytesKeyGenerator} that returns a single, shared {@link SecureRandom} key of a custom length.
* @param keyLength the key length in bytes, e.g. 16, for a 16 byte key.
*/
public static BytesKeyGenerator shared(int keyLength) {
return new SharedKeyGenerator(secureRandom(keyLength).generateKey());
}
/**
* Creates a {@link StringKeyGenerator} that hex-encodes {@link SecureRandom} keys of 8 bytes in length.
* The hex-encoded string is keyLength * 2 characters in length.
*/
public static StringKeyGenerator string() {
return new HexEncodingStringKeyGenerator(secureRandom());
}
// internal helpers
private KeyGenerators() {
}
}
@@ -1,63 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
/**
* A KeyGenerator that uses {@link SecureRandom} to generate byte array-based keys.
* <p>
* No specific provider is used for the {@code SecureRandom}, so the platform default
* will be used.
*
* @author Keith Donald
*/
final class SecureRandomBytesKeyGenerator implements BytesKeyGenerator {
private final SecureRandom random;
private final int keyLength;
/**
* Creates a secure random key generator using the defaults.
*/
public SecureRandomBytesKeyGenerator() {
this(DEFAULT_KEY_LENGTH);
}
/**
* Creates a secure random key generator with a custom key length.
*/
public SecureRandomBytesKeyGenerator(int keyLength) {
this.random = new SecureRandom();
this.keyLength = keyLength;
}
public int getKeyLength() {
return keyLength;
}
public byte[] generateKey() {
byte[] bytes = new byte[keyLength];
random.nextBytes(bytes);
return bytes;
}
private static final int DEFAULT_KEY_LENGTH = 8;
}
@@ -1,41 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
/**
* Key generator that simply returns the same key every time.
*
* @author Keith Donald
* @author Annabelle Donald
* @author Corgan Donald
*/
final class SharedKeyGenerator implements BytesKeyGenerator {
private byte[] sharedKey;
public SharedKeyGenerator(byte[] sharedKey) {
this.sharedKey = sharedKey;
}
public int getKeyLength() {
return sharedKey.length;
}
public byte[] generateKey() {
return sharedKey;
}
}
@@ -1,26 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.keygen;
/**
* A generator for unique string keys.
* @author Keith Donald
*/
public interface StringKeyGenerator {
String generateKey();
}
@@ -1,59 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.password;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
/**
* Helper for working with the MessageDigest API.
*
* Performs the configured number of iterations of the hashing algorithm per digest to aid in protecting against brute force attacks.
*
* @author Keith Donald
* @author Luke Taylor
*/
final class Digester {
private final MessageDigest messageDigest;
private final int iterations;
/**
* Create a new Digester.
* @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
* @param iterations the number of times to apply the digest algorithm to the input
*/
public Digester(String algorithm, int iterations) {
try {
messageDigest = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("No such hashing algorithm", e);
}
this.iterations = iterations;
}
public byte[] digest(byte[] value) {
synchronized (messageDigest) {
for (int i = 0; i < iterations; i++) {
value = messageDigest.digest(value);
}
return value;
}
}
}
@@ -1,46 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.password;
/**
* A password encoder that does nothing.
* Useful for testing where working with plain text passwords may be preferred.
*
* @author Keith Donald
*/
public final class NoOpPasswordEncoder implements PasswordEncoder {
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}
/**
* Get the singleton {@link NoOpPasswordEncoder}.
*/
public static PasswordEncoder getInstance() {
return INSTANCE;
}
private static final PasswordEncoder INSTANCE = new NoOpPasswordEncoder();
private NoOpPasswordEncoder() {
}
}
@@ -1,42 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.password;
/**
* Service interface for encoding passwords.
* @author Keith Donald
*/
public interface PasswordEncoder {
/**
* Encode the raw password.
* Generally, a good encoding algorithm applies a SHA-1 or greater hash combined with an 8-byte or greater randomly
* generated salt.
*/
String encode(CharSequence rawPassword);
/**
* Verify the encoded password obtained from storage matches the submitted raw password after it too is encoded.
* Returns true if the passwords match, false if they do not.
* The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);
}
@@ -1,109 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.password;
import static org.springframework.security.crypto.util.EncodingUtils.concatenate;
import static org.springframework.security.crypto.util.EncodingUtils.subArray;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.crypto.keygen.BytesKeyGenerator;
import org.springframework.security.crypto.keygen.KeyGenerators;
/**
* A standard {@code PasswordEncoder} implementation that uses SHA-256 hashing with 1024 iterations and a
* random 8-byte random salt value. It uses an additional system-wide secret value to provide additional protection.
* <p>
* The digest algorithm is invoked on the concatenated bytes of the salt, secret and password.
*
* @author Keith Donald
* @author Luke Taylor
*/
public final class StandardPasswordEncoder implements PasswordEncoder {
private final Digester digester;
private final byte[] secret;
private final BytesKeyGenerator saltGenerator;
/**
* Constructs a standard password encoder with no additional secret value.
*/
public StandardPasswordEncoder() {
this("");
}
/**
* Constructs a standard password encoder with a secret value which is also included in the
* password hash.
*
* @param secret the secret key used in the encoding process (should not be shared)
*/
public StandardPasswordEncoder(CharSequence secret) {
this("SHA-256", secret);
}
public String encode(CharSequence rawPassword) {
return encode(rawPassword, saltGenerator.generateKey());
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
byte[] digested = decode(encodedPassword);
byte[] salt = subArray(digested, 0, saltGenerator.getKeyLength());
return matches(digested, digest(rawPassword, salt));
}
// internal helpers
private StandardPasswordEncoder(String algorithm, CharSequence secret) {
this.digester = new Digester(algorithm, DEFAULT_ITERATIONS);
this.secret = Utf8.encode(secret);
this.saltGenerator = KeyGenerators.secureRandom();
}
private String encode(CharSequence rawPassword, byte[] salt) {
byte[] digest = digest(rawPassword, salt);
return new String(Hex.encode(digest));
}
private byte[] digest(CharSequence rawPassword, byte[] salt) {
byte[] digest = digester.digest(concatenate(salt, secret, Utf8.encode(rawPassword)));
return concatenate(salt, digest);
}
private byte[] decode(CharSequence encodedPassword) {
return Hex.decode(encodedPassword);
}
/**
* Constant time comparison to prevent against timing attacks.
*/
private boolean matches(byte[] expected, byte[] actual) {
if (expected.length != actual.length) {
return false;
}
int result = 0;
for (int i = 0; i < expected.length; i++) {
result |= expected[i] ^ actual[i];
}
return result == 0;
}
private static final int DEFAULT_ITERATIONS = 1024;
}
@@ -1,60 +0,0 @@
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.crypto.util;
/**
* Static helper for encoding data.
* <p>
* For internal use only.
*
* @author Keith Donald
*/
public class EncodingUtils {
/**
* Combine the individual byte arrays into one array.
*/
public static byte[] concatenate(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
byte[] newArray = new byte[length];
int destPos = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, newArray, destPos, array.length);
destPos += array.length;
}
return newArray;
}
/**
* Extract a sub array of bytes out of the byte array.
* @param array the byte array to extract from
* @param beginIndex the beginning index of the sub array, inclusive
* @param endIndex the ending index of the sub array, exclusive
*/
public static byte[] subArray(byte[] array, int beginIndex, int endIndex) {
int length = endIndex - beginIndex;
byte[] subarray = new byte[length];
System.arraycopy(array, beginIndex, subarray, 0, length);
return subarray;
}
private EncodingUtils() {
}
}
@@ -1,25 +0,0 @@
package org.springframework.security.crypto.codec;
import static org.junit.Assert.*;
import org.junit.*;
import java.util.*;
/**
* @author Luke Taylor
*/
public class Utf8Tests {
// SEC-1752
@Test
public void utf8EncodesAndDecodesCorrectly() throws Exception {
byte[] bytes = Utf8.encode("6048b75ed560785c");
assertEquals(16, bytes.length);
assertTrue(Arrays.equals("6048b75ed560785c".getBytes("UTF-8"), bytes));
String decoded = Utf8.decode(bytes);
assertEquals("6048b75ed560785c", decoded);
}
}
@@ -1,48 +0,0 @@
package org.springframework.security.crypto.encrypt;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class EncryptorsTests {
@Test
public void standard() throws Exception {
BytesEncryptor encryptor = Encryptors.standard("password", "5c0744940b5c369b");
byte[] result = encryptor.encrypt("text".getBytes("UTF-8"));
assertNotNull(result);
assertFalse(new String(result).equals("text"));
assertEquals("text", new String(encryptor.decrypt(result)));
assertFalse(new String(result).equals(new String(encryptor.encrypt("text".getBytes()))));
}
@Test
public void text() {
TextEncryptor encryptor = Encryptors.text("password", "5c0744940b5c369b");
String result = encryptor.encrypt("text");
assertNotNull(result);
assertFalse(result.equals("text"));
assertEquals("text", encryptor.decrypt(result));
assertFalse(result.equals(encryptor.encrypt("text")));
}
@Test
public void queryableText() {
TextEncryptor encryptor = Encryptors.queryableText("password", "5c0744940b5c369b");
String result = encryptor.encrypt("text");
assertNotNull(result);
assertFalse(result.equals("text"));
assertEquals("text", encryptor.decrypt(result));
assertTrue(result.equals(encryptor.encrypt("text")));
}
@Test
public void noOpText() {
TextEncryptor encryptor = Encryptors.noOpText();
assertEquals("text", encryptor.encrypt("text"));
assertEquals("text", encryptor.decrypt("text"));
}
}
@@ -1,52 +0,0 @@
package org.springframework.security.crypto.keygen;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
public class KeyGeneratorsTests {
@Test
public void secureRandom() {
BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom();
assertEquals(8, keyGenerator.getKeyLength());
byte[] key = keyGenerator.generateKey();
assertEquals(8, key.length);
byte[] key2 = keyGenerator.generateKey();
assertFalse(Arrays.equals(key, key2));
}
@Test
public void secureRandomCustomLength() {
BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(21);
assertEquals(21, keyGenerator.getKeyLength());
byte[] key = keyGenerator.generateKey();
assertEquals(21, key.length);
byte[] key2 = keyGenerator.generateKey();
assertFalse(Arrays.equals(key, key2));
}
@Test
public void shared() throws Exception {
BytesKeyGenerator keyGenerator = KeyGenerators.shared(21);
assertEquals(21, keyGenerator.getKeyLength());
byte[] key = keyGenerator.generateKey();
assertEquals(21, key.length);
byte[] key2 = keyGenerator.generateKey();
assertTrue(Arrays.equals(key, key2));
}
@Test
public void string() {
StringKeyGenerator keyGenerator = KeyGenerators.string();
String hexStringKey = keyGenerator.generateKey();
assertEquals(16, hexStringKey.length());
assertEquals(8, Hex.decode(hexStringKey).length);
String hexStringKey2 = keyGenerator.generateKey();
assertFalse(hexStringKey.equals(hexStringKey2));
}
}
@@ -1,24 +0,0 @@
package org.springframework.security.crypto.password;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.security.MessageDigest;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.crypto.password.Digester;
public class DigesterTests {
@Test
public void digestIsCorrectFor3Iterations() {
Digester digester = new Digester("SHA-1", 3);
byte[] result = digester.digest(Utf8.encode("text"));
// echo -n text | openssl sha1 -binary | openssl sha1 -binary | openssl sha1
assertEquals("3cfa28da425eca5b894f0af2b158adf7001e000f", new String(Hex.encode(result)));
}
}
@@ -1,31 +0,0 @@
package org.springframework.security.crypto.password;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class StandardPasswordEncoderTests {
private StandardPasswordEncoder encoder = new StandardPasswordEncoder("secret");
@Test
public void matches() {
String result = encoder.encode("password");
assertFalse(result.equals("password"));
assertTrue(encoder.matches("password", result));
}
@Test
public void matchesLengthChecked() {
String result = encoder.encode("password");
assertFalse(encoder.matches("password", result.substring(0,result.length()-2)));
}
@Test
public void notMatches() {
String result = encoder.encode("password");
assertFalse(encoder.matches("bogus", result));
}
}
@@ -1,45 +0,0 @@
package org.springframework.security.crypto.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import org.junit.Test;
import org.springframework.security.crypto.codec.Hex;
public class EncodingUtilsTests {
@Test
public void hexEncode() {
byte[] bytes = new byte[] { (byte)0x01, (byte)0xFF, (byte)65, (byte)66, (byte)67, (byte)0xC0, (byte)0xC1, (byte)0xC2 };
String result = new String(Hex.encode(bytes));
assertEquals("01ff414243c0c1c2", result);
}
@Test
public void hexDecode() {
byte[] bytes = new byte[] { (byte)0x01, (byte)0xFF, (byte)65, (byte)66, (byte)67, (byte)0xC0, (byte)0xC1, (byte)0xC2 };
byte[] result = Hex.decode("01ff414243c0c1c2");
assertTrue(Arrays.equals(bytes, result));
}
@Test
public void concatenate() {
byte[] bytes = new byte[] { (byte)0x01, (byte)0xFF, (byte)65, (byte)66, (byte)67, (byte)0xC0, (byte)0xC1, (byte)0xC2 };
byte[] one = new byte[] { (byte)0x01 };
byte[] two = new byte[] { (byte)0xFF, (byte)65, (byte)66 };
byte[] three = new byte[] { (byte)67, (byte)0xC0, (byte)0xC1, (byte)0xC2 };
assertTrue(Arrays.equals(bytes, EncodingUtils.concatenate(one, two, three)));
}
@Test
public void subArray() {
byte[] bytes = new byte[] { (byte)0x01, (byte)0xFF, (byte)65, (byte)66, (byte)67, (byte)0xC0, (byte)0xC1, (byte)0xC2 };
byte[] two = new byte[] { (byte)0xFF, (byte)65, (byte)66 };
byte[] subArray = EncodingUtils.subArray(bytes, 1, 4);
assertEquals(3, subArray.length);
assertTrue(Arrays.equals(two, subArray));
}
}