Class CryptoHelper
- java.lang.Object
-
- org.owasp.esapi.crypto.CryptoHelper
-
public class CryptoHelper extends java.lang.ObjectClass to provide some convenience methods for encryption, decryption, etc.All the cryptographic operations use the default cryptographic properties; e.g., default cipher transformation, default key size, default IV type (where applicable), etc.
- Since:
- 2.0
- Author:
- kevin.w.wall@gmail.com
-
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static booleanarrayCompare(byte[] b1, byte[] b2)Deprecated.Use java.security.MessageDigest#isEqual(byte[], byte[]) instead.static javax.crypto.SecretKeycomputeDerivedKey(javax.crypto.SecretKey keyDerivationKey, int keySize, java.lang.String purpose)Deprecated.Use same method inKeyDerivationFunctioninstead.static voidcopyByteArray(byte[] src, byte[] dest)Same ascopyByteArray(src, dest, src.length).static voidcopyByteArray(byte[] src, byte[] dest, int length)Same asSystem.arraycopy(src, 0, dest, 0, length).static javax.crypto.SecretKeygenerateSecretKey(java.lang.String alg, int keySize)Generate a random secret key appropriate to the specified cipher algorithm and key size.static booleanisAllowedCipherMode(java.lang.String cipherMode)Return true if specified cipher mode is one that may be used for encryption / decryption operations viaEncryptor.static booleanisCipherTextMACvalid(javax.crypto.SecretKey sk, CipherText ct)If a Message Authentication Code (MAC) is required for the specifiedCipherTextobject, then attempt to validate the MAC that should be embedded within theCipherTextobject by using a derived key based on the specifiedSecretKey.static booleanisCombinedCipherMode(java.lang.String cipherMode)Return true if specified cipher mode is one of those specified in theESAPI.propertiesfile that supports both confidentiality and authenticity (i.e., a "combined cipher mode" as NIST refers to it).static booleanisMACRequired(CipherText ct)Check to see if a Message Authentication Code (MAC) is required for a givenCipherTextobject and the current ESAPI.property settings.static booleanisValidKDFVersion(int kdfVers, boolean restrictToCurrent, boolean throwIfError)Is this particular KDF version number one that is sane? For that, we just make sure it is inbounds of the valid range which is:static voidoverwrite(byte[] bytes)Overwrite a byte array with the byte containing '*'.static voidoverwrite(byte[] bytes, byte x)Overwrite a byte array with a specified byte.
-
-
-
Method Detail
-
generateSecretKey
public static javax.crypto.SecretKey generateSecretKey(java.lang.String alg, int keySize) throws EncryptionExceptionGenerate a random secret key appropriate to the specified cipher algorithm and key size.- Parameters:
alg- The cipher algorithm or cipher transformation. (If the latter is passed, the cipher algorithm is determined from it.) Cannot be null or empty.keySize- The key size, in bits.- Returns:
- A random
SecretKeyis returned. - Throws:
EncryptionException- Thrown if cannot create secret key conforming to requested algorithm with requested size. Typically this is caused by specifying an unavailable algorithm or invalid key size.
-
computeDerivedKey
@Deprecated public static javax.crypto.SecretKey computeDerivedKey(javax.crypto.SecretKey keyDerivationKey, int keySize, java.lang.String purpose) throws java.security.NoSuchAlgorithmException, java.security.InvalidKeyException, EncryptionExceptionDeprecated.Use same method inKeyDerivationFunctioninstead. This method will be removed as of ESAPI release 2.3 so if you are using this, please CHANGE YOUR CODE. Note that the replacement is not a static method, so create your own wrapper if you wish, but this will soon disappear.The method is ESAPI's Key Derivation Function (KDF) that computes a derived key from thekeyDerivationKeyfor either encryption / decryption or for authentication.CAUTION: If this algorithm for computing derived keys from the key derivation key is ever changed, we risk breaking backward compatibility of being able to decrypt data previously encrypted with earlier / different versions of this method. Therefore, do not change this unless you are 100% certain that what you are doing will NOT change either of the derived keys for ANY "key derivation key" AT ALL!!!
NOTE: This method is generally not intended to be called separately. It is used by ESAPI's reference crypto implementation class
JavaEncryptorand might be useful for someone implementing their own replacement class, but generally it is not something that is useful to application client code.- Parameters:
keyDerivationKey- A key used as an input to a key derivation function to derive other keys. This is the key that generally is created using some key generation mechanism such asgenerateSecretKey(String, int). The "input" key from which the other keys are derived. The derived key will have the same algorithm type as this key.keySize- The cipher's key size (in bits) for thekeyDerivationKey. Must have a minimum size of 56 bits and be an integral multiple of 8-bits. Note: The derived key will have the same size as this.purpose- The purpose for the derived key. Must be either the string "encryption" or "authenticity". Use "encryption" for creating a derived key to use for confidentiality, and "authenticity" for a derived key to use with a MAC to ensure message authenticity.- Returns:
- The derived
SecretKeyto be used according to the specified purpose. Note that this serves the same purpose as "label" in section 5.1 of NIST SP 800-108. - Throws:
java.security.NoSuchAlgorithmException- ThekeyDerivationKeyhas an unsupported encryption algorithm or no current JCE provider supports "HmacSHA1".EncryptionException- If "UTF-8" is not supported as an encoding, then this is thrown with the originalUnsupportedEncodingExceptionas the cause. (NOTE: This should never happen as "UTF-8" is supposed to be a common encoding supported by all Java implementations. Support for it is usually in rt.jar.) This exception is also thrown if the requestedkeySizeparameter exceeds the length of the number of bytes provded in thekeyDerivationKeyparameter.java.security.InvalidKeyException- Likely indicates a coding error. Should not happen.EncryptionException- Throw for some precondition violations.
-
isCombinedCipherMode
public static boolean isCombinedCipherMode(java.lang.String cipherMode)
Return true if specified cipher mode is one of those specified in theESAPI.propertiesfile that supports both confidentiality and authenticity (i.e., a "combined cipher mode" as NIST refers to it).- Parameters:
cipherMode- The specified cipher mode to be used for the encryption or decryption operation.- Returns:
- true if the specified cipher mode is in the comma-separated list of cipher modes supporting both confidentiality and authenticity; otherwise false.
- See Also:
SecurityConfiguration.getCombinedCipherModes()
-
isAllowedCipherMode
public static boolean isAllowedCipherMode(java.lang.String cipherMode)
Return true if specified cipher mode is one that may be used for encryption / decryption operations viaEncryptor.- Parameters:
cipherMode- The specified cipher mode to be used for the encryption or decryption operation.- Returns:
- true if the specified cipher mode is in the comma-separated list of cipher modes supporting both confidentiality and authenticity; otherwise false.
- See Also:
isCombinedCipherMode(String),SecurityConfiguration.getCombinedCipherModes(),SecurityConfiguration.getAdditionalAllowedCipherModes()
-
isMACRequired
public static boolean isMACRequired(CipherText ct)
Check to see if a Message Authentication Code (MAC) is required for a givenCipherTextobject and the current ESAPI.property settings. A MAC is considered "required" if the specifiedCipherTextwas not encrypted by one of the preferred "combined" cipher modes (e.g., CCM or GCM) and the setting of the current ESAPI properties for the propertyEncryptor.CipherText.useMACis set totrue. (Normally, the setting forEncryptor.CipherText.useMACshould be set totrueunless FIPS 140-2 compliance is required. See User Guide for Symmetric Encryption in ESAPI 2.0 and the section on using ESAPI with FIPS for further details.- Parameters:
ct- The specifiedCipherTextobject to check to see if it requires a MAC.- Returns:
- True if a MAC is required, false if it is not required.
-
isCipherTextMACvalid
public static boolean isCipherTextMACvalid(javax.crypto.SecretKey sk, CipherText ct)If a Message Authentication Code (MAC) is required for the specifiedCipherTextobject, then attempt to validate the MAC that should be embedded within theCipherTextobject by using a derived key based on the specifiedSecretKey.- Parameters:
sk- TheSecretKeyused to derived a key to check the authenticity via the MAC.ct- TheCipherTextthat we are checking for a valid MAC.- Returns:
- True is returned if a MAC is required and it is valid as
verified using a key derived from the specified
SecretKeyor a MAC is not required. False is returned otherwise.
-
overwrite
public static void overwrite(byte[] bytes, byte x)Overwrite a byte array with a specified byte. This is frequently done to a plaintext byte array so the sensitive data is not lying around exposed in memory.- Parameters:
bytes- The byte array to be overwritten.x- The byte arraybytesis overwritten with this byte.
-
overwrite
public static void overwrite(byte[] bytes)
Overwrite a byte array with the byte containing '*'. That is, calloverwrite(bytes, (byte)'*');- Parameters:
bytes- The byte array to be overwritten.
-
copyByteArray
public static void copyByteArray(byte[] src, byte[] dest, int length)Same asSystem.arraycopy(src, 0, dest, 0, length).- Parameters:
src- the source array.dest- the destination array.length- the number of array elements to be copied.- Throws:
java.lang.IndexOutOfBoundsException- if copying would cause access of data outside array bounds.java.lang.NullPointerException- if eithersrcordestisnull.
-
copyByteArray
public static void copyByteArray(byte[] src, byte[] dest)Same ascopyByteArray(src, dest, src.length).- Parameters:
src- the source array.dest- the destination array.- Throws:
java.lang.IndexOutOfBoundsException- if copying would cause access of data outside array bounds.java.lang.NullPointerException- if eithersrcordestisnull.
-
arrayCompare
@Deprecated public static boolean arrayCompare(byte[] b1, byte[] b2)Deprecated.Use java.security.MessageDigest#isEqual(byte[], byte[]) instead.A "safe" array comparison that is not vulnerable to side-channel "timing attacks". All comparisons of non-null, equal length bytes should take same amount of time. We use this for cryptographic comparisons.- Parameters:
b1- A byte array to compare.b2- A second byte array to compare.- Returns:
trueif both byte arrays are null or if both byte arrays are identical or have the same value; otherwisefalseis returned.
-
isValidKDFVersion
public static boolean isValidKDFVersion(int kdfVers, boolean restrictToCurrent, boolean throwIfError) throws java.lang.IllegalArgumentExceptionIs this particular KDF version number one that is sane? For that, we just make sure it is inbounds of the valid range which is:[20110203, 99991231]- Parameters:
kdfVers- KDF version # that we are checking. Generally this is extracted from the serializedCipherText.restrictToCurrent- If this is set, we do an additional check to see if the KDF version is a later version than the one that this current ESAPI version supports.throwIfError- Instead of returningfalsein the case of an error, throw anIllegalArgumentException- Returns:
- True if in range, false otherwise (except if
throwIfErroris true.} - Throws:
java.lang.IllegalArgumentException
-
-