Java Code Examples for javax.crypto.Cipher#getMaxAllowedKeyLength()
The following examples show how to use
javax.crypto.Cipher#getMaxAllowedKeyLength() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CipherSuite.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
private static boolean isUnlimited(int keySize, String transformation) { int keySizeInBits = keySize * 8; if (keySizeInBits > 128) { // need the JCE unlimited // strength jurisdiction policy try { if (Cipher.getMaxAllowedKeyLength( transformation) < keySizeInBits) { return false; } } catch (Exception e) { return false; } } return true; }
Example 2
Source File: CICOPBEFuncTest.java From hottub with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { for (PBEAlgorithm algorithm : PBEAlgorithm.values()) { // int buffertin test String algo = algorithm.baseAlgo.toUpperCase(); if (!algo.contains("TRIPLEDES") && !algo.contains("AES_256") || Cipher.getMaxAllowedKeyLength(algo) > 128) { // skip this if this key length is larger than what's // configured in the jce jurisdiction policy files System.out.println("Testing " + algorithm.getTransformation()); for (String type : Arrays.asList(CICO_PBE_Test.INT_BYTE_BUFFER, CICO_PBE_Test.BYTE_ARR_BUFFER)) { new CICO_PBE_RW_Test(algorithm) .proceedTest(type); new CICO_PBE_SKIP_Test(algorithm) .proceedTest(type); } } } }
Example 3
Source File: CICOPBEFuncTest.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { for (PBEAlgorithm algorithm : PBEAlgorithm.values()) { // int buffertin test String algo = algorithm.baseAlgo.toUpperCase(); if (!algo.contains("TRIPLEDES") && !algo.contains("AES_256") || Cipher.getMaxAllowedKeyLength(algo) > 128) { // skip this if this key length is larger than what's // configured in the jce jurisdiction policy files System.out.println("Testing " + algorithm.getTransformation()); for (String type : Arrays.asList(CICO_PBE_Test.INT_BYTE_BUFFER, CICO_PBE_Test.BYTE_ARR_BUFFER)) { new CICO_PBE_RW_Test(algorithm) .proceedTest(type); new CICO_PBE_SKIP_Test(algorithm) .proceedTest(type); } } } }
Example 4
Source File: CICOPBEFuncTest.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { for (PBEAlgorithm algorithm : PBEAlgorithm.values()) { // int buffertin test String algo = algorithm.baseAlgo.toUpperCase(); if (!algo.contains("TRIPLEDES") && !algo.contains("AES_256") || Cipher.getMaxAllowedKeyLength(algo) > 128) { // skip this if this key length is larger than what's // configured in the jce jurisdiction policy files System.out.println("Testing " + algorithm.getTransformation()); for (String type : Arrays.asList(CICO_PBE_Test.INT_BYTE_BUFFER, CICO_PBE_Test.BYTE_ARR_BUFFER)) { new CICO_PBE_RW_Test(algorithm) .proceedTest(type); new CICO_PBE_SKIP_Test(algorithm) .proceedTest(type); } } } }
Example 5
Source File: Encrypt.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { Provider p = Security.getProvider("SunJCE"); for (String alg : ALGORITHMS) { for (int keyStrength : KEY_STRENGTHS) { if (keyStrength > Cipher.getMaxAllowedKeyLength(alg)) { // skip this if this key length is larger than what's // configured in the JCE jurisdiction policy files continue; } for (int textLength : TEXT_LENGTHS) { for (int AADLength : AAD_LENGTHS) { Encrypt test = new Encrypt(p, alg, "GCM", "NoPadding", keyStrength, textLength, AADLength); Cipher cipher = test.createCipher(Cipher.ENCRYPT_MODE, null); AlgorithmParameters params = cipher.getParameters(); test.doTest(params); System.out.println("Test " + alg + ":" + keyStrength + ":" + textLength + ":" + AADLength + " passed"); } } } } }
Example 6
Source File: AESCTRNoPaddingProvider.java From mt-flume with Apache License 2.0 | 6 votes |
private static Cipher getCipher(Key key, int mode, byte[] parameters) { try { Cipher cipher = Cipher.getInstance(TYPE); cipher.init(mode, key, new IvParameterSpec(parameters)); return cipher; } catch (Exception e) { String msg = "Unable to load key using transformation: " + TYPE; if (e instanceof InvalidKeyException) { try { int maxAllowedLen = Cipher.getMaxAllowedKeyLength(TYPE); if (maxAllowedLen < 256) { msg += "; Warning: Maximum allowed key length = " + maxAllowedLen + " with the available JCE security policy files. Have you" + " installed the JCE unlimited strength jurisdiction policy" + " files?"; } } catch (NoSuchAlgorithmException ex) { msg += "; Unable to find specified algorithm?"; } } LOG.error(msg, e); throw Throwables.propagate(e); } }
Example 7
Source File: TestCipherKeyWrapperTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, NoSuchAlgorithmException { for (String alg : PBE_ALGORITHM_AR) { String baseAlgo = alg.split("/")[0].toUpperCase(); // only run the tests on longer key lengths if unlimited version // of JCE jurisdiction policy files are installed if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE && (baseAlgo.endsWith("TRIPLEDES") || alg .endsWith("AES_256"))) { out.println("keyStrength > 128 within " + alg + " will not run under global policy"); continue; } SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p); SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover" .toCharArray())); wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true); } }
Example 8
Source File: ReadWriteSkip.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { boolean success = true; for (int keyLength : KEY_LENGTHS) { if (keyLength > Cipher.getMaxAllowedKeyLength(TRANSFORM)) { // skip this if this key length is larger than what's // configured in the jce jurisdiction policy files continue; } for (int textLength : TXT_LENGTHS) { for (int AADLength : AAD_LENGTHS) { System.out.println("Key length = " + keyLength + ", text length = " + textLength + ", AAD length = " + AADLength); try { run(keyLength, textLength, AADLength); System.out.println("Test case passed"); } catch (Exception e) { System.out.println("Test case failed: " + e); success = false; } } } } if (!success) { throw new RuntimeException("At least one test case failed"); } System.out.println("Test passed"); }
Example 9
Source File: GCMParameterSpecTest.java From hottub with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { boolean success = true; for (int k : KEY_LENGTHS) { if (k > Cipher.getMaxAllowedKeyLength(TRANSFORMATION)) { // skip this if this key length is larger than what's // allowed in the jce jurisdiction policy files continue; } for (int t : TAG_LENGTHS) { for (int n : IV_LENGTHS) { for (int p : DATA_LENGTHS) { for (int a : AAD_LENGTHS) { for (int o : OFFSETS) { System.out.printf(TEMPLATE, t, n, p, a, o, k); success &= new GCMParameterSpecTest( k, t, n, o, p, a).doTest(); } } } } } } if (!success) { throw new RuntimeException("At least one test case failed"); } }
Example 10
Source File: EncryptionUtil.java From Dream-Catcher with MIT License | 5 votes |
/** * Determines if unlimited-strength cryptography is allowed, i.e. if this JRE has then the unlimited strength policy * files installed. * * @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; } }
Example 11
Source File: DefaultDhisConfigurationProvider.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public EncryptionStatus getEncryptionStatus() { String password; int maxKeyLength; // Check for JCE files is present (key length > 128) and AES is available try { maxKeyLength = Cipher.getMaxAllowedKeyLength( "AES" ); if ( maxKeyLength == 128 ) { return EncryptionStatus.MISSING_JCE_POLICY; } } catch ( NoSuchAlgorithmException e ) { return EncryptionStatus.MISSING_JCE_POLICY; } password = getProperty( ConfigurationKey.ENCRYPTION_PASSWORD ); if ( password.length() == 0 ) { return EncryptionStatus.MISSING_ENCRYPTION_PASSWORD; } if ( password.length() < 24 ) { return EncryptionStatus.ENCRYPTION_PASSWORD_TOO_SHORT; } return EncryptionStatus.OK; }
Example 12
Source File: CipherStrengthAction.java From constellation with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(ActionEvent e) { try { final int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES"); final String msg = String.format("Maximum key length: %s", maxKeyLen == Integer.MAX_VALUE ? "unlimited" : Integer.toString(maxKeyLen)); final NotifyDescriptor nd = new NotifyDescriptor.Message(msg, NotifyDescriptor.INFORMATION_MESSAGE); DialogDisplayer.getDefault().notify(nd); } catch (NoSuchAlgorithmException ex) { Exceptions.printStackTrace(ex); } }
Example 13
Source File: AesKwTest.java From azure-keyvault-java with MIT License | 5 votes |
private static boolean hasUnlimitedCrypto() { try { return Cipher.getMaxAllowedKeyLength("RC5") >= 256; } catch (NoSuchAlgorithmException e) { return false; } }
Example 14
Source File: NiFiPropertiesLoader.java From localization_nifi with Apache License 2.0 | 5 votes |
private static String getDefaultProviderKey() { try { return "aes/gcm/" + (Cipher.getMaxAllowedKeyLength("AES") > 128 ? "256" : "128"); } catch (NoSuchAlgorithmException e) { return "aes/gcm/128"; } }
Example 15
Source File: Dynamic.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
protected boolean runTest(String algo, String mo, String pad) throws Exception { boolean result = true; try { byte[] plainText = new byte[160000]; new Random().nextBytes(plainText); String transformation = algo + "/" + mo + "/" + pad; ci = Cipher.getInstance(transformation, SUNJCE); KeyGenerator kg = KeyGenerator.getInstance(algo, SUNJCE); if (keyStrength > Cipher.getMaxAllowedKeyLength(transformation)) { // skip if this key length is larger than what's // configured in the jce jurisdiction policy files System.out.println(keyStrength + " is larger than what's configured " + "in the jce jurisdiction policy files"); return result; } kg.init(keyStrength); key = kg.generateKey(); if (!mo.equalsIgnoreCase("GCM")) { ci.init(Cipher.ENCRYPT_MODE, key, aps); } else { ci.init(Cipher.ENCRYPT_MODE, key); } byte[] cipherText = new byte[ci.getOutputSize(plainText.length)]; int offset = ci.update(plainText, 0, plainText.length, cipherText, 0); ci.doFinal(cipherText, offset); ci.init(Cipher.DECRYPT_MODE, key, ci.getParameters()); byte[] recoveredText = new byte[ci.getOutputSize(cipherText.length)]; int len = ci.doFinal(cipherText, 0, cipherText.length, recoveredText); byte[] tmp = new byte[len]; for (int i = 0; i < len; i++) { tmp[i] = recoveredText[i]; } result = Arrays.equals(plainText, tmp); } catch (NoSuchAlgorithmException nsaEx) { // CFB7 and OFB150 are negative test,SunJCE not support this // algorithm result = mo.equalsIgnoreCase("CFB7") || mo.equalsIgnoreCase("OFB150"); if (!result) { // only report unexpected exception nsaEx.printStackTrace(); } } return result; }
Example 16
Source File: TestCipherPBE.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
private void runTest(String algorithm) throws InvalidKeySpecException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, ShortBufferException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { out.println("=> Testing: " + algorithm); boolean isUnlimited = (Cipher.getMaxAllowedKeyLength(algorithm) == Integer.MAX_VALUE); try { // Initialization AlgorithmParameterSpec algoParamSpec = new PBEParameterSpec(SALT, 6); SecretKey secretKey = SecretKeyFactory.getInstance(KEY_ALGO).generateSecret( new PBEKeySpec(("Secret Key Value").toCharArray())); Cipher ci = Cipher.getInstance(algorithm); ci.init(Cipher.ENCRYPT_MODE, secretKey, algoParamSpec); // Encryption byte[] cipherText = ci.doFinal(PLAIN_TEXT); // Decryption ci.init(Cipher.DECRYPT_MODE, secretKey, algoParamSpec); byte[] recoveredText = ci.doFinal(cipherText); if (algorithm.contains("TripleDES") && !isUnlimited) { throw new RuntimeException( "Expected InvalidKeyException not thrown"); } // Comparison if (!Arrays.equals(PLAIN_TEXT, recoveredText)) { throw new RuntimeException( "Test failed: plainText is not equal to recoveredText"); } out.println("Test Passed."); } catch (InvalidKeyException ex) { if (algorithm.contains("TripleDES") && !isUnlimited) { out.println("Expected InvalidKeyException thrown"); } else { throw new RuntimeException(ex); } } }
Example 17
Source File: PBECipherWrapper.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
@Override public boolean execute(int edMode, byte[] inputText, int offset, int len) { StringTokenizer st = new StringTokenizer(algo, "/"); String baseAlgo = st.nextToken().toUpperCase(); boolean isUnlimited; try { isUnlimited = (Cipher.getMaxAllowedKeyLength(this.algo) == Integer.MAX_VALUE); } catch (NoSuchAlgorithmException nsae) { out.println("Got unexpected exception for " + this.algo); nsae.printStackTrace(out); return false; } // Perform encryption or decryption depends on the specified edMode try { ci.init(edMode, key, aps); if ((baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) && !isUnlimited) { out.print("Expected InvalidKeyException not thrown: " + this.algo); return false; } // First, generate the cipherText at an allocated buffer byte[] outputText = ci.doFinal(inputText, offset, len); // Second, generate cipherText again at the same buffer of // plainText int myoff = offset / 2; int off = ci.update(inputText, offset, len, inputText, myoff); ci.doFinal(inputText, myoff + off); // Compare to see whether the two results are the same or not boolean result = equalsBlock(inputText, myoff, outputText, 0, outputText.length); return result; } catch (Exception ex) { if ((ex instanceof InvalidKeyException) && (baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) && !isUnlimited) { out.println("Expected InvalidKeyException thrown for " + algo); return true; } else { out.println("Got unexpected exception for " + algo); ex.printStackTrace(out); return false; } } }
Example 18
Source File: TestCipherKeyWrapperPBEKey.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
public boolean runTest(Provider p, String algo, PrintStream out) throws Exception { byte[] salt = new byte[8]; int ITERATION_COUNT = 1000; AlgorithmParameters pbeParams = null; String baseAlgo = new StringTokenizer(algo, "/").nextToken().toUpperCase(); boolean isAES = baseAlgo.contains("AES"); boolean isUnlimited = (Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE); try { // Initialization new Random().nextBytes(salt); AlgorithmParameterSpec aps = new PBEParameterSpec(salt, ITERATION_COUNT); SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p); SecretKey key = skf.generateSecret(new PBEKeySpec( "Secret Key".toCharArray())); Cipher ci = Cipher.getInstance(algo); if (isAES) { ci.init(Cipher.WRAP_MODE, key); pbeParams = ci.getParameters(); } else { ci.init(Cipher.WRAP_MODE, key, aps); } byte[] keyWrapper = ci.wrap(key); if (isAES) { ci.init(Cipher.UNWRAP_MODE, key, pbeParams); } else { ci.init(Cipher.UNWRAP_MODE, key, aps); } Key unwrappedKey = ci.unwrap(keyWrapper, algo, Cipher.SECRET_KEY); if ((baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) && !isUnlimited) { out.print( "Expected InvalidKeyException not thrown"); return false; } return (Arrays.equals(key.getEncoded(), unwrappedKey.getEncoded())); } catch (InvalidKeyException ex) { if ((baseAlgo.endsWith("TRIPLEDES") || baseAlgo.endsWith("AES_256")) && !isUnlimited) { out.print( "Expected InvalidKeyException thrown"); return true; } else { throw ex; } } }
Example 19
Source File: TestCipherKeyWrapperTest.java From TencentKona-8 with GNU General Public License v2.0 | 4 votes |
private void wrapperBlowfishKeyTest() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException { // how many kinds of padding mode int padKinds; // Keysize should be multiple of 8 bytes. int KeyCutter = 8; int kSize = BLOWFISH_MIN_KEYSIZE; String algorithm = "Blowfish"; int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm); boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE; SecretKey key = null; while (kSize <= BLOWFISH_MAX_KEYSIZE) { for (String mode : MODEL_AR) { // PKCS5padding is meaningful only for ECB, CBC, PCBC if (mode.equalsIgnoreCase(MODEL_AR[0]) || mode.equalsIgnoreCase(MODEL_AR[1]) || mode.equalsIgnoreCase(MODEL_AR[2])) { padKinds = PADDING_AR.length; } else { padKinds = 1; } // Initialization KeyGenerator kg = KeyGenerator.getInstance(algorithm); for (int k = 0; k < padKinds; k++) { String transformation = algorithm + "/" + mode + "/" + PADDING_AR[k]; if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) { out.println(transformation + " will not run if input length not multiple" + " of 8 bytes when padding is " + NOPADDING); continue; } kg.init(kSize); key = kg.generateKey(); // only run the tests on longer key lengths if unlimited // version of JCE jurisdiction policy files are installed if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) { out.println("keyStrength > 128 within " + algorithm + " will not run under global policy"); } else { wrapTest(transformation, transformation, key, key, Cipher.SECRET_KEY, false); } } } if (kSize <= LINIMITED_KEYSIZE) { KeyCutter = 8; } else { KeyCutter = 48; } kSize += KeyCutter; } }
Example 20
Source File: TestCipherKeyWrapperTest.java From jdk8u_jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { TestCipherKeyWrapperTest test = new TestCipherKeyWrapperTest(); // AESWrap and DESedeWrap test for (AlgorithmWrapper algoWrapper : AlgorithmWrapper.values()) { String algo = algoWrapper.getAlgorithm(); String wrapper = algoWrapper.getWrapper(); try { int keySize = algoWrapper.getKeySize(); // only run the tests on longer key lengths if unlimited // version of JCE jurisdiction policy files are installed if (!(Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE) && keySize > LINIMITED_KEYSIZE) { out.println(algo + " will not run if unlimited version of" + " JCE jurisdiction policy files are installed"); continue; } test.wrapperAesDESedeKeyTest(algo, wrapper, keySize); if (algoWrapper == AlgorithmWrapper.NegtiveWrap) { throw new RuntimeException("Expected not throw when algo" + " and wrapAlgo are not match:" + algo); } } catch (InvalidKeyException e) { if (algoWrapper == AlgorithmWrapper.NegtiveWrap) { out.println("Expepted exception when algo" + " and wrapAlgo are not match:" + algo); } else { throw e; } } } test.wrapperBlowfishKeyTest(); // PBE and public wrapper test. String[] publicPrivateAlgos = new String[] { "DiffieHellman", "DSA", "RSA" }; Provider provider = Security.getProvider(SUN_JCE); if (provider == null) { throw new RuntimeException("SUN_JCE provider not exist"); } test.wrapperPBEKeyTest(provider); // Public and private key wrap test test.wrapperPublicPriviteKeyTest(provider, publicPrivateAlgos); }