org.owasp.esapi.crypto
Class CryptoToken

java.lang.Object
  extended by org.owasp.esapi.crypto.CryptoToken

public class CryptoToken
extends java.lang.Object

Compute a cryptographically secure, encrypted token containing optional name/value pairs. The cryptographic token is computed like this:

     username;expiration_time;[<attr1>;<attr2>;...;<attrN>;]
 
where username is a user account name. Defaults to <anonymous> if not set and it is always converted to lower case as per the rules of the default locale. (Note this lower case conversion is consistent with the default reference implementation of ESAPI's User interface.)
expiration_time is time (in milliseconds) after which the encrypted token is considered invalid (i.e., expired). The time is stored as milliseconds since midnight, January 1, 1970 UTC, and optional attributes
  <attr1>;<attr2>;...<attrN>;
are optional semicolon (';') separated name/value pairs, where each name/value pair has the form:
         name=[value]        (value may be empty, but not null)
 
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 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
          [A-Za-z0-9_\.-]+
 
The attribute value on the other hand, may be any valid string. (That is, the value is not checked, so beware!)

This entire semicolon-separated string is then encrypted via one of the Encryptor.encrypt() methods and then base64-encoded, serialized IV + ciphertext + MAC representation as determined by CipherTextasPortableSerializedByteArray() is used as the resulting cryptographic token.

The attributes are sorted by attribute name and the attribute names must be unique. There are some restrictions on the attribute names. (See the setAttribute(String, String) method for details.)

Since:
2.0
Author:
[email protected]

Field Summary
static java.lang.String ANONYMOUS_USER
          Represents an anonymous user.
 
Constructor Summary
CryptoToken()
          Create a cryptographic token using default secret key from the ESAPI.properties property Encryptor.MasterKey.
CryptoToken(javax.crypto.SecretKey skey)
          Create a cryptographic token using specified SecretKey.
CryptoToken(javax.crypto.SecretKey skey, java.lang.String token)
          Create cryptographic token using previously encrypted token that was encrypted with specified secret key.
CryptoToken(java.lang.String token)
          Create using previously encrypted token encrypted with default secret key from ESAPI.properties.
 
Method Summary
 void addAttributes(java.util.Map<java.lang.String,java.lang.String> attrs)
          Add the specified collection of attributes to the current attributes.
 void clearAttributes()
          Removes all the attributes (if any) associated with this token.
 java.lang.String getAttribute(java.lang.String name)
          Retrieve the attribute with the specified name.
 java.util.Map<java.lang.String,java.lang.String> getAttributes()
          Retrieve a Map that is a clone of all the attributes.
 long getExpiration()
          Return the expiration time in milliseconds since epoch time (midnight, January 1, 1970 UTC).
 java.util.Date getExpirationDate()
          Return the expiration time as a Date.
 java.lang.String getToken()
          Return the new encrypted token as a base64-encoded string, encrypted with the specified SecretKey with which this object was constructed.
 java.lang.String getToken(javax.crypto.SecretKey skey)
          Return the new encrypted token as a base64-encoded string, encrypted with the specified SecretKey which may be a different key than what the token was originally encrypted with.
 java.lang.String getUserAccountName()
          Retrieve the user account name associated with this CryptoToken object.
 boolean isExpired()
          Check if token has expired yet.
 void setAttribute(java.lang.String name, java.lang.String value)
          Set a name/value pair as an attribute.
 void setExpiration(java.util.Date expirationDate)
          Set expiration time for a specific date/time.
 void setExpiration(int intervalSecs)
          Set expiration time to expire in 'interval' seconds (NOT milliseconds).
 void setUserAccountName(java.lang.String userAccountName)
          Set the user account name associated with this cryptographic token object.
 java.lang.String updateToken(int additionalSecs)
          Update the (current) expiration time by adding the specified number of seconds to it and then re-encrypting with the current SecretKey that was used to construct this object.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ANONYMOUS_USER

public static final java.lang.String ANONYMOUS_USER
Represents an anonymous user.

See Also:
Constant Field Values
Constructor Detail

CryptoToken

public CryptoToken()
Create a cryptographic token using default secret key from the ESAPI.properties property Encryptor.MasterKey.


CryptoToken

public CryptoToken(javax.crypto.SecretKey skey)
Create a cryptographic token using specified SecretKey.

Parameters:
skey - The specified SecretKey to use to encrypt the token.

CryptoToken

public CryptoToken(java.lang.String token)
            throws EncryptionException
Create using previously encrypted token encrypted with default secret key from ESAPI.properties.

Parameters:
token - A previously encrypted token returned by one of the getToken() or updateToken() methods. The token must have been previously encrypted using the using default secret key from the ESAPI.properties property Encryptor.MasterKey.
Throws:
EncryptionException - Thrown if they are any problems while decrypting the token using the default secret key from ESAPI.properties or if the decrypted token is not properly formatted.

CryptoToken

public CryptoToken(javax.crypto.SecretKey skey,
                   java.lang.String token)
            throws EncryptionException
Create cryptographic token using previously encrypted token that was encrypted with specified secret key.

Parameters:
token - A previously encrypted token returned by one of the getToken() or updateToken() methods.
Throws:
EncryptionException - Thrown if they are any problems while decrypting the token using the default secret key from ESAPI.properties or if the decrypted token is not properly formatted.
Method Detail

getUserAccountName

public java.lang.String getUserAccountName()
Retrieve the user account name associated with this CryptoToken object.

Returns:
The user account name. The string represented by ANONYMOUS_USER is returned if setUserAccountName(String) was never called.

setUserAccountName

public void setUserAccountName(java.lang.String userAccountName)
                        throws ValidationException
Set the user account name associated with this cryptographic token object. The user account name is converted to lower case.

Parameters:
userAccountName - The user account name.
Throws:
ValidationException - Thrown if user account name is not valid, i.e., if it doesn't conform to the regular expression given by "[a-z][a-z0-9_.@-]*". (Note that the parameter userAccountName is first converted to lower case before checked against the regular expression.)

isExpired

public boolean isExpired()
Check if token has expired yet.

Returns:
True if token has expired; false otherwise.

setExpiration

public void setExpiration(int intervalSecs)
                   throws java.lang.IllegalArgumentException
Set expiration time to expire in 'interval' seconds (NOT milliseconds).

Parameters:
interval - Number of seconds in the future from current date/time to set expiration. Must be positive.
Throws:
java.lang.IllegalArgumentException

setExpiration

public void setExpiration(java.util.Date expirationDate)
                   throws java.lang.IllegalArgumentException
Set expiration time for a specific date/time.

Parameters:
expirationDate - The date/time at which the token will fail. Must be after the current date/time.
Throws:
java.lang.IllegalArgumentException - Thrown if the parameter is null.

getExpiration

public long getExpiration()
Return the expiration time in milliseconds since epoch time (midnight, January 1, 1970 UTC).

Returns:
The current expiration time.

getExpirationDate

public java.util.Date getExpirationDate()
Return the expiration time as a Date.

Returns:
The Date object representing the expiration time.

setAttribute

public void setAttribute(java.lang.String name,
                         java.lang.String value)
                  throws ValidationException
Set a name/value pair as an attribute.

Parameters:
name - The attribute name
value - The attribute value
Throws:
ValidationException - Thrown if the attribute name is not properly formed. That is, the attribute name does not match the regular expression "[A-Za-z0-9_.-]+".

addAttributes

public void addAttributes(java.util.Map<java.lang.String,java.lang.String> attrs)
                   throws ValidationException
Add the specified collection of attributes to the current attributes. If there are duplicate attributes specified, they will replace any existing ones.

Parameters:
attrs - Name/value pairs of attributes to add or replace the existing attributes. Map must be non-null, but may be empty.
Throws:
ValidationException - Thrown if one of the keys in the specified parameter attrs is not a valid name. That is, all attribute names must match the regular expression ""[A-Za-z0-9_.-]+".
See Also:
setAttribute(String, String)

getAttribute

public java.lang.String getAttribute(java.lang.String name)
Retrieve the attribute with the specified name.

Parameters:
name - The attribute name.
Returns:
The value associated with the attribute name. If attribute is not set, then null is returned.

getAttributes

public java.util.Map<java.lang.String,java.lang.String> getAttributes()
Retrieve a Map that is a clone of all the attributes. A copy is returned so that the attributes in CrytpToken are unaffected by alterations made the returned Map. (Otherwise, multi-threaded code could get trick.

Returns:
A Map of all the attributes.
See Also:
getAttribute(String)

clearAttributes

public void clearAttributes()
Removes all the attributes (if any) associated with this token. Note that this does not clear / reset the user account name or expiration time.


getToken

public java.lang.String getToken(javax.crypto.SecretKey skey)
                          throws EncryptionException
Return the new encrypted token as a base64-encoded string, encrypted with the specified SecretKey which may be a different key than what the token was originally encrypted with. E.g.,
   Alice:
      SecretKey aliceSecretKey = ...; // Shared with Bob
      CryptoToken cryptoToken = new CryptoToken(skey1);
      cryptoToken.setUserAccountName("kwwall");
      cryptoToken.setAttribute("role", "admin");
      cryptoToken.setAttribute("state", "Ohio");
      String token = cryptoToken.getToken(); // Encrypted with skey1
      // send token to Bob ...
  --------------------------------------------------------------------
  Bob:
      ...
      SecretKey aliceSecretKey = ...  // Shared with Alice
      SecretKey bobSecretKey = ...;   // Shared with Carol
      CryptoToken cryptoToken = new CryptoToken(aliceSecretKey, tokenFromAlice);
      
      // Re-encrypt for Carol using my (Bob's) key...
      String tokenForCarol = cryptoToken.getToken(bobSecretKey);
      // send tokenForCarol to Carol ...
      // use token ourselves
  --------------------------------------------------------------------
  Carol:
      ...
      SecretKey bobSecretKey = ...;   // Shared with Bob.
      CryptoToken cryptoToken = new CryptoToken(bobSecretKey, tokenFromBob);
      if ( ! cryptoToken.isExpired() ) {
          String userName = cryptoToken.getUserAccountName();
          String roleName = cryptoToken.getAttribute("role");
          if ( roleName != null && roleName.equalsIgnoreCase("admin") ) {
              // grant admin access...
              ...
          }
      }
      ...
 

Parameters:
skey - The specified key to (re)encrypt the token.
Returns:
The newly encrypted token.
Throws:
EncryptionException

updateToken

public java.lang.String updateToken(int additionalSecs)
                             throws EncryptionException,
                                    ValidationException
Update the (current) expiration time by adding the specified number of seconds to it and then re-encrypting with the current SecretKey that was used to construct this object.

Parameters:
additionalSecs - The additional number of seconds to add to the current expiration time. This number must be >= 0 or otherwise an IllegalArgumentException is thrown.
Returns:
The re-encrypted token with the updated expiration time is returned.
Throws:
java.lang.IllegalArgumentException - Thrown if parameter additionalSecs is less than 0.
EncryptionException - Thrown if the encryption fails.
ValidationException - Thrown if the token will have already expired even after adding the specified number of additional seconds.
java.lang.ArithmeticException - If additional seconds is large enough such that it would cause an arithmetic overflow with a long (the current expiration time) when added to the additionalSecs parameter.

getToken

public java.lang.String getToken()
                          throws EncryptionException
Return the new encrypted token as a base64-encoded string, encrypted with the specified SecretKey with which this object was constructed.

Returns:
The newly encrypted token.
Throws:
EncryptionException
See Also:
getToken(SecretKey)


Copyright © 2011 The Open Web Application Security Project (OWASP). All Rights Reserved.