Example usage for javax.crypto Cipher getMaxAllowedKeyLength

List of usage examples for javax.crypto Cipher getMaxAllowedKeyLength

Introduction

In this page you can find the example usage for javax.crypto Cipher getMaxAllowedKeyLength.

Prototype

public static final int getMaxAllowedKeyLength(String transformation) throws NoSuchAlgorithmException 

Source Link

Document

Returns the maximum key length for the specified transformation according to the installed JCE jurisdiction policy files.

Usage

From source file:Main.java

/**
 * Determines if unlimited-strength cryptography is allowed, i.e. if this JRE has then the unlimited strength policy
 * files installed./* w ww  .j  av a  2  s .c  om*/
 *
 * @return true if unlimited strength cryptography is allowed, otherwise false
 */
public static boolean isUnlimitedStrengthAllowed() {
    try {
        return Cipher.getMaxAllowedKeyLength("AES") >= 256;
    } catch (NoSuchAlgorithmException e) {
        return false;
    }

}

From source file:com.microsoft.azure.keyvault.cryptography.test.SymmetricKeyTest.java

private static boolean hasUnlimitedCrypto() {
    try {/* w ww  .  ja  va 2s.com*/
        return Cipher.getMaxAllowedKeyLength("RC5") >= 256;
    } catch (NoSuchAlgorithmException e) {
        return false;
    }
}

From source file:mitm.common.security.JCEPolicyManager.java

/**
 * Returns true if the JCE unlimited strength jurisdiction policy files are installed.
 *//*ww  w. j av  a  2s  .  co m*/
public static boolean isUnlimitedStrength() {
    boolean unlimited = false;

    try {
        int maxAllowed = Cipher.getMaxAllowedKeyLength("AES");

        unlimited = maxAllowed == Integer.MAX_VALUE;
    } catch (NoSuchAlgorithmException e) {
        logger.warn("Unable to instantiate cipher.");
    }

    return unlimited;
}

From source file:de.siegmar.securetransfer.component.Cryptor.java

/**
 * Ensure that we have strong cryptography extension (JCE) installed.
 *///from  w w w. j av  a 2 s .c  o m
private void validateCipherKeyLength() {
    try {
        final int keyLength = Cipher.getMaxAllowedKeyLength("AES");
        if (keyLength < MIN_KEY_LENGTH) {
            throw new IllegalStateException("MaxAllowedKeyLength for AES is " + keyLength + "! "
                    + "Either install JCE for Oracle JDK or use OpenJDK.");
        }
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

private static CryptoStrength unlimitedStrengthTest() {
    try {//from   w  ww .ja v a 2s  .  co m
        if (Cipher.getMaxAllowedKeyLength("AES") >= 256) {
            return UNLIMITED;
        }
    } catch (NoSuchAlgorithmException e) {
        // swallow exception
    }
    return LIMITED;
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 *///from   w w w  .j a va  2  s.  c o m
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}

From source file:br.com.vectorx.BlowfishCryptox.java

/**
 * Construtor private. Define o tamanho mximo da palavra salt de acordo com
 * o SecurityPolice instalado//from w  w  w . j av a  2  s .  c o  m
 * 
 * @param palavraChave
 *            Palavra chave
 * @param algoritmo
 *            Algoritmo a ser utilizado (no caso o Blowfish)
 * @param cifraCesar
 *            em quantos numeros os caracteres sero trocados
 * @param charset
 * @throws IllegalArgumentException
 */
private BlowfishCryptox(String palavraChave, String algoritmo, int cifraCesar, Charset charset)
        throws IllegalArgumentException {
    try {
        int maxSalt = LIMITEDSALTLENGTH;
        // Checagem para ver se tem JCE Unlimited Strength Policy instalado
        if (Cipher.getMaxAllowedKeyLength(algoritmo) > BlowfishCryptox.CIFRAMAX) {
            maxSalt = BlowfishCryptox.UNLIMITEDJCESALT;
        }
        validateInput(palavraChave, cifraCesar, maxSalt);
        this.charset = charset;
        SecretKey chave = new SecretKeySpec(palavraChave.getBytes(charset), algoritmo);
        this.encrypt = Cipher.getInstance(algoritmo);
        this.decrypt = Cipher.getInstance(algoritmo);
        this.encrypt.init(Cipher.ENCRYPT_MODE, chave);
        this.decrypt.init(Cipher.DECRYPT_MODE, chave);
        this.cifraCesar = cifraCesar;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.commonjava.util.jhttpc.unit.HttpFactoryTest.java

@Test
@Ignore("This is a diagnostic test for the environment, mainly for use with the docker-driven test below")
public void checkKeyStrength() throws NoSuchAlgorithmException {
    int allowedKeyLength = 0;

    assertThat("The allowed key length for AES is: " + allowedKeyLength + ", should be > 128!",
            Cipher.getMaxAllowedKeyLength("AES") > 128, equalTo(true));

    System.out.println("The allowed key length for AES is: " + allowedKeyLength);
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

protected void validateKey(Key key) throws InvalidKeyException, NoSuchAlgorithmException {
    String algorithm = key.getAlgorithm();
    int size = key.getEncoded().length * 8;
    if (!KEY_ALGORITHM.equalsIgnoreCase(algorithm)) {
        String msg = "Expected key of type: " + KEY_ALGORITHM + ", instead it was: " + algorithm;
        log.error(msg);//  w w w  .j a v  a2s.  c  om
        throw new InvalidKeyException(msg);
    } else if (size > Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM)) {
        String msg = "Illegal key size, max platform support for " + KEY_ALGORITHM + " keys is "
                + Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM);
        log.error(msg);
        throw new InvalidKeyException(msg);
    }
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Decrypting text that is encrypted by the advanced encryption standard.
 *
 * @param password The char array containing of the plaintext password
 * @param encryptedBlock The Encrypted text to be targeted and decrypted.
 *
 * @return The decrypted byte array of the encrypted text.
 *//*from  w ww. j  av  a2s  .c o  m*/
public byte[] decrypt(char[] password, char[] encryptedBlock)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, DecoderException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password with the MD5 function and decode the encryptedBlock
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] decoded = Hex.decodeHex(encryptedBlock);

    // The decoded byte array has the IV, encryptedText, and salt bytes stored in that order.
    // The IV bytes are of length 16 and salt is of length 20.
    byte[] encryptedText = new byte[decoded.length - 36], ivBytes = new byte[16], salt = new byte[20];

    // The decoded bytes are ordered in the following form: ivBytes + encryptedText + saltBytes.
    // Extract the bytes into their corresponding array.
    System.arraycopy(decoded, 0, ivBytes, 0, ivBytes.length);
    System.arraycopy(decoded, ivBytes.length, encryptedText, 0, encryptedText.length);
    System.arraycopy(decoded, decoded.length - salt.length, salt, 0, salt.length);

    // generate the key from the acquired data
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // finally, attempt to decrypt the encryptedText
    cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
    return cipher.doFinal(encryptedText);
}