Java Code Examples for javax.crypto.Cipher#getParameters()

The following examples show how to use javax.crypto.Cipher#getParameters() . 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: AESPBEWrapper.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object using given "mode".
 * @return a cipher object.
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // get Cipher instance
    Cipher ci = Cipher.getInstance(transformation, provider);
    if (Cipher.ENCRYPT_MODE == mode) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        pbeParams = ci.getParameters();
    } else {
        ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
    }
    return ci;
}
 
Example 2
Source File: AESPBEWrapper.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object using given "mode".
 * @return a cipher object.
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // get Cipher instance
    Cipher ci = Cipher.getInstance(transformation, provider);
    if (Cipher.ENCRYPT_MODE == mode) {
        ci.init(Cipher.ENCRYPT_MODE, key);
        pbeParams = ci.getParameters();
    } else {
        ci.init(Cipher.DECRYPT_MODE, key, pbeParams);
    }
    return ci;
}
 
Example 3
Source File: Encrypt.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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 4
Source File: ScopedKeys.java    From KeenClient-Java with MIT License 5 votes vote down vote up
/**
 * Encrypts the given options with a Keen API Key and creates a Scoped Key.
 *
 * @param client  The KeenClient to use for JSON handling.
 * @param apiKey  Your Keen API Key.
 * @param options The options you want to encrypt.
 * @return A Keen Scoped Key.
 * @throws ScopedKeyException an error occurred while attempting to encrypt a Scoped Key.
 */
public static String encrypt32CharacterKey(KeenClient client, String apiKey, Map<String, Object> options)
    throws ScopedKeyException {
    try {
        // if the user doesn't give an options, just use an empty one
        if (options == null) {
            options = new HashMap<String, Object>();
        }

        // pad the api key
        final String paddedApiKey = padApiKey(apiKey);

        // json encode the options
        StringWriter writer = new StringWriter();
        client.getJsonHandler().writeJson(writer, options);
        final String jsonOptions = writer.toString();

        // setup the API key as the secret
        final SecretKey secret = new SecretKeySpec(paddedApiKey.getBytes("UTF-8"), "AES");

        // get the right AES cipher
        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        final AlgorithmParameters params = cipher.getParameters();
        // get a random IV for each encryption
        final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        // do the actual encryption (this also pads jsonOptions)
        final byte[] cipherText = cipher.doFinal(jsonOptions.getBytes("UTF-8"));

        // now return the hexed iv + the hexed cipher text
        return KeenUtils.byteArrayToHexString(iv) + KeenUtils.byteArrayToHexString(cipherText);
    } catch (Exception e) {
        throw new ScopedKeyException("An error occurred while attempting to encrypt a Scoped Key", e);
    }
}
 
Example 5
Source File: SecretManager.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * Encrypt plaintext.
 * @param str Plaintext to encrypt
 * @return Cipher text
 */
public String encrypt(final String str) {
    if (str == null) {
        throw new NullPointerException("Argument cannot be null");
    }

    try {
        final SecureRandom random = new SecureRandom();
        final byte[] salt = new byte[16];
        random.nextBytes(salt);

        final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        final KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 65536, 128);
        final SecretKey tmp = factory.generateSecret(spec);
        final SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        final AlgorithmParameters params = cipher.getParameters();
        final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        final byte[] encryptedText = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));

        // concatenate salt + iv + cipher text
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(salt);
        outputStream.write(iv);
        outputStream.write(encryptedText);

        // properly encode the complete cipher text
        return DatatypeConverter.printBase64Binary(outputStream.toByteArray());
    } catch (final Exception exception) {
        throw new RuntimeException(exception.getMessage(), exception);
    }
}
 
Example 6
Source File: SampleIDs.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Encrypt an integer to a String.
 * 
 * @param integer
 * @param context
 * @return
 * @throws ServletException
 */
private static String encryptInteger(Integer integer, ServletContext context) throws ServletException {
	/* Get password. */
	String password = context.getInitParameter("SampleSetIDEncryptionPassword");

	/* Generate salt. */
	SecureRandom rand = new SecureRandom();
	byte salt[] = new byte[8];
	rand.nextBytes(salt);

	byte[] iv;
	byte[] ciphertext;
	try {
		/* Derive the key, given password and salt. */
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
		SecretKey tmp = factory.generateSecret(spec);
		SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		/* Encrypt the SampleSetID. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		iv = params.getParameterSpec(IvParameterSpec.class).getIV();
		ciphertext = cipher.doFinal(ByteBuffer.allocate(4).putInt(integer).array());
	} catch (Exception ex) {
		throw new ServletException(ex);
	}

	/* Store the encrypted SampleSetID in a cookie */

	Encoder encoder = Base64.getEncoder();
	String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
	return encryptedStr;
}
 
Example 7
Source File: TextPKCS5PaddingTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider not exist");
    }
    // generate no-padding cipher with secret key
    Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider);
    KeyGenerator kgen = KeyGenerator.getInstance("DES", provider);
    SecretKey skey = kgen.generateKey();
    // this is the improperly padded plaintext

    c.init(Cipher.ENCRYPT_MODE, skey);
    // encrypt plaintext
    byte[] cipher = c.doFinal(PLAIN_TEXT);
    AlgorithmParameters params = c.getParameters();
    // generate cipher that enforces PKCS5 padding
    c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider);
    c.init(Cipher.DECRYPT_MODE, skey, params);
    try {
        c.doFinal(cipher);
        throw new RuntimeException(
                "ERROR: Expected BadPaddingException not thrown");
    } catch (BadPaddingException expected) {
        out.println("Expected BadPaddingException thrown");
    }

}
 
Example 8
Source File: Encryption.java    From browserprint with MIT License 5 votes vote down vote up
/**
 * Encrypt an array of integers to a String.
 * 
 * @param integers
 * @param context
 * @return
 * @throws ServletException
 */
public static String encryptIntegers(int integers[], String password) throws ServletException {
	/* Generate salt. */
	SecureRandom rand = new SecureRandom();
	byte salt[] = new byte[8];
	rand.nextBytes(salt);

	byte[] iv;
	byte[] ciphertext;
	try {
		/* Derive the key, given password and salt. */
		SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
		KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
		SecretKey tmp = factory.generateSecret(spec);
		SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

		/* Encrypt the SampleSetID. */
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		iv = params.getParameterSpec(IvParameterSpec.class).getIV();

		ByteBuffer buff = ByteBuffer.allocate(integers.length * 4);
		for (int i = 0; i < integers.length; ++i) {
			buff.putInt(integers[i]);
		}
		ciphertext = cipher.doFinal(buff.array());
	} catch (Exception ex) {
		throw new ServletException(ex);
	}

	/* Store the encrypted SampleSetID in a cookie */

	Encoder encoder = Base64.getEncoder();
	String encryptedStr = encoder.encodeToString(ciphertext) + "|" + encoder.encodeToString(iv) + "|" + encoder.encodeToString(salt);
	return encryptedStr;
}
 
Example 9
Source File: SameBuffer.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void runTest(Provider p, String algo, String mode,
        String padding, int keyLength, int textLength, int AADLength,
        int offset) throws Exception {
    System.out.println("Testing " + keyLength + " key length; "
            + textLength + " text lenght; " + AADLength + " AAD length; "
            + offset + " offset");
    if (keyLength > Cipher.getMaxAllowedKeyLength(algo)) {
        // skip this if this key length is larger than what's
        // configured in the jce jurisdiction policy files
        return;
    }
    SameBuffer test = new SameBuffer(p, algo, mode,
            padding, keyLength, textLength, AADLength);

    /*
     * There are four test cases:
     *   1. AAD and text are placed in separated byte arrays
     *   2. AAD and text are placed in the same byte array
     *   3. AAD and text are placed in separated byte buffers
     *   4. AAD and text are placed in the same byte buffer
     */
    Cipher ci = test.createCipher(Cipher.ENCRYPT_MODE, null);
    AlgorithmParameters params = ci.getParameters();
    test.doTestWithSeparateArrays(offset, params);
    test.doTestWithSameArrays(offset, params);
    test.doTestWithSeparatedBuffer(offset, params);
    test.doTestWithSameBuffer(offset, params);
}
 
Example 10
Source File: ValueEncryptionUtilities.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This salts and encrypts a value and returns a base64 encoded version of the encrypted value.
 * @param value The value to be encrypted.
 * @param length The number on bytes to expand out to the source value to. This is so that all encryption
 *               operations generate the same length output. Watch out for multibyte characters as these will mean
 *               that your length must be more than the number of character in the string. If 0 then no padding is
 *               done.
 * @return A salted base64 encrypted version of the value.
 * @throws RuntimeException If encryption fails for any reason.
 */
public String encrypt(String value, int length) {
	try {
		byte[] salt = getSalt();
		SecretKey secret = getSecret(key, salt, getKeyLength());
		Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		//get IV from cipher parameters
		IvParameterSpec parameterSpec = params.getParameterSpec(IvParameterSpec.class);
		// AES always has 128bit IV
		byte[] iv = parameterSpec.getIV();
		byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
		if (length != 0 && bytes.length > length) {
			throw new IllegalArgumentException("Can't encode as it's longer than our fixed length.");
		}
		int finalLength = (length == 0)?bytes.length: length;
		byte[] source = new byte[finalLength];
		System.arraycopy(bytes, 0, source, 0, bytes.length);
		// Fill the remainded of the array with illegal UTF-8 characters.
		Arrays.fill(source, bytes.length, source.length, (byte) UTF_8_ILLEGAL);
		byte[] ciphertext = cipher.doFinal(source);

		//create final array (in bytes) : IV + SALT + TEXT
		byte[] finalCiphertext = new byte[ciphertext.length+2*16];
		System.arraycopy(iv, 0, finalCiphertext, 0, 16);
		System.arraycopy(salt, 0, finalCiphertext, 16, 16);
		System.arraycopy(ciphertext, 0, finalCiphertext, 32, ciphertext.length);
		//encode all bytes in a Base64 string
		return encoder.encodeToString(finalCiphertext);
	} catch(Exception e){
		// We must not log out the value here so that the plaintext can't accidentally end up in the logs
		log.error("Error while encrypting.", e);
		return null;
	}
}
 
Example 11
Source File: SameBuffer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void runTest(Provider p, String algo, String mode,
        String padding, int keyLength, int textLength, int AADLength,
        int offset) throws Exception {
    System.out.println("Testing " + keyLength + " key length; "
            + textLength + " text lenght; " + AADLength + " AAD length; "
            + offset + " offset");
    if (keyLength > Cipher.getMaxAllowedKeyLength(algo)) {
        // skip this if this key length is larger than what's
        // configured in the jce jurisdiction policy files
        return;
    }
    SameBuffer test = new SameBuffer(p, algo, mode,
            padding, keyLength, textLength, AADLength);

    /*
     * There are four test cases:
     *   1. AAD and text are placed in separated byte arrays
     *   2. AAD and text are placed in the same byte array
     *   3. AAD and text are placed in separated byte buffers
     *   4. AAD and text are placed in the same byte buffer
     */
    Cipher ci = test.createCipher(Cipher.ENCRYPT_MODE, null);
    AlgorithmParameters params = ci.getParameters();
    test.doTestWithSeparateArrays(offset, params);
    test.doTestWithSameArrays(offset, params);
    test.doTestWithSeparatedBuffer(offset, params);
    test.doTestWithSameBuffer(offset, params);
}
 
Example 12
Source File: SimpleEncryption.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static String encrypt(String key, String source) {
	if (source == null) {
		return null;
	}

	byte[] salt = new byte[8];
	new Random().nextBytes(salt);
	char[] password = key.toCharArray();

	try {
		SecretKey secret = generateSecret(password, salt);
		/* Encrypt the message. */
		Cipher cipher = Cipher.getInstance(CIPHER);
		cipher.init(Cipher.ENCRYPT_MODE, secret);
		AlgorithmParameters params = cipher.getParameters();
		byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();

		byte[] ciphertext = cipher.doFinal(source.getBytes("UTF-8"));
		
		// Pack the byte arrays into a string hex encoded. 
		StringBuffer out = new StringBuffer();
		out.append(LegacyShaUtil.byteToHex(salt));
		out.append(":");
		out.append(LegacyShaUtil.byteToHex(iv));
		out.append(":");
		out.append(LegacyShaUtil.byteToHex(ciphertext));
		out.append(":");
		out.append(CIPHER);
		return out.toString();
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 13
Source File: SameBuffer.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static void runTest(Provider p, String algo, String mode,
        String padding, int keyLength, int textLength, int AADLength,
        int offset) throws Exception {
    System.out.println("Testing " + keyLength + " key length; "
            + textLength + " text lenght; " + AADLength + " AAD length; "
            + offset + " offset");
    if (keyLength > Cipher.getMaxAllowedKeyLength(algo)) {
        // skip this if this key length is larger than what's
        // configured in the jce jurisdiction policy files
        return;
    }
    SameBuffer test = new SameBuffer(p, algo, mode,
            padding, keyLength, textLength, AADLength);

    /*
     * There are four test cases:
     *   1. AAD and text are placed in separated byte arrays
     *   2. AAD and text are placed in the same byte array
     *   3. AAD and text are placed in separated byte buffers
     *   4. AAD and text are placed in the same byte buffer
     */
    Cipher ci = test.createCipher(Cipher.ENCRYPT_MODE, null);
    AlgorithmParameters params = ci.getParameters();
    test.doTestWithSeparateArrays(offset, params);
    test.doTestWithSameArrays(offset, params);
    test.doTestWithSeparatedBuffer(offset, params);
    test.doTestWithSameBuffer(offset, params);
}
 
Example 14
Source File: EciesTest.java    From wycheproof with Apache License 2.0 5 votes vote down vote up
/**
 * Encryption with ByteBuffers.
 * This test failed with BouncyCastle v 1.52 probably because of this bug
 * http://www.bouncycastle.org/jira/browse/BJA-577
 */
@Test
public void testByteBuffer() throws Exception {
  ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
  // TODO(bleichen): Not sure what is better here:
  //   BouncyCastle allows EC and ECIES. So far I can't see a difference.
  //   In both cases the test is broken for version 1.52.
  KeyPairGenerator kf = KeyPairGenerator.getInstance("ECIES");
  kf.initialize(ecSpec);
  KeyPair keyPair = kf.generateKeyPair();
  PrivateKey priv = keyPair.getPrivate();
  PublicKey pub = keyPair.getPublic();
  byte[] message = "Hello".getBytes("UTF-8");

  // Encryption
  Cipher cipher = Cipher.getInstance("ECIESwithAES-CBC");
  cipher.init(Cipher.ENCRYPT_MODE, pub);
  AlgorithmParameters params = cipher.getParameters();
  ByteBuffer ptBuffer = ByteBuffer.wrap(message);
  ByteBuffer ctBuffer = ByteBuffer.allocate(1024);
  cipher.doFinal(ptBuffer, ctBuffer);

  // Decryption
  ctBuffer.flip();
  ByteBuffer decrypted = ByteBuffer.allocate(message.length);
  cipher.init(Cipher.DECRYPT_MODE, priv, params);
  cipher.doFinal(ctBuffer, decrypted);
  assertEquals(TestUtil.bytesToHex(message), TestUtil.bytesToHex(decrypted.array()));
}
 
Example 15
Source File: TestSymmCiphersNoPad.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void main(Provider p) throws Exception {
    boolean status = true;
    Random random = new Random();
    try {
        for (int i = 0; i < TEST_LIST.length; i++) {
            CI currTest = TEST_LIST[i];
            System.out.println("===" + currTest.transformation + "===");
            try {
                KeyGenerator kg =
                    KeyGenerator.getInstance(currTest.keyAlgo, p);
                SecretKey key = kg.generateKey();
                Cipher c1 = Cipher.getInstance(currTest.transformation, p);
                Cipher c2 = Cipher.getInstance(currTest.transformation,
                                               "SunJCE");

                byte[] plainTxt = new byte[currTest.dataSize];
                random.nextBytes(plainTxt);
                System.out.println("Testing inLen = " + plainTxt.length);

                c2.init(Cipher.ENCRYPT_MODE, key);
                AlgorithmParameters params = c2.getParameters();
                byte[] answer = c2.doFinal(plainTxt);
                test(c1, Cipher.ENCRYPT_MODE, key, params,
                     plainTxt, answer);
                System.out.println("Encryption tests: DONE");
                c2.init(Cipher.DECRYPT_MODE, key, params);
                byte[] answer2 = c2.doFinal(answer);
                test(c1, Cipher.DECRYPT_MODE, key, params,
                     answer, answer2);
                System.out.println("Decryption tests: DONE");
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println("Skipping unsupported algorithm: " +
                                   nsae);
            }
        }
    } catch (Exception ex) {
        // print out debug info when exception is encountered
        if (debugBuf != null) {
            System.out.println(debugBuf.toString());
        }
        throw ex;
    }
}
 
Example 16
Source File: TestCipherKeyWrapperPBEKey.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
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 17
Source File: TestCipherKeyWrapperPBEKey.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
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 18
Source File: PKCS12KeyStore.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
private byte[] encryptContent(byte[] data, char[] password)
    throws IOException {

    byte[] encryptedData = null;


    try {
        // create AlgorithmParameters
        AlgorithmParameters algParams = getPBEAlgorithmParameters(
                certProtectionAlgorithm, certPbeIterationCount);
        DerOutputStream bytes = new DerOutputStream();

        // Use JCE
        SecretKey skey = getPBEKey(password);
        Cipher cipher = Cipher.getInstance(certProtectionAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
        encryptedData = cipher.doFinal(data);

        AlgorithmId algId = new AlgorithmId(
                mapPBEAlgorithmToOID(certProtectionAlgorithm),
                cipher.getParameters());
                // cipher.getParameters() now has IV
        algId.encode(bytes);
        byte[] encodedAlgId = bytes.toByteArray();

        if (debug != null) {
            debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() +
                    ")");
        }

        // create EncryptedContentInfo
        DerOutputStream bytes2 = new DerOutputStream();
        bytes2.putOID(ContentInfo.DATA_OID);
        bytes2.write(encodedAlgId);

        // Wrap encrypted data in a context-specific tag.
        DerOutputStream tmpout2 = new DerOutputStream();
        tmpout2.putOctetString(encryptedData);
        bytes2.writeImplicit(DerValue.createTag(DerValue.TAG_CONTEXT,
                false, (byte) 0), tmpout2);

        // wrap EncryptedContentInfo in a Sequence
        DerOutputStream out = new DerOutputStream();
        out.write(DerValue.tag_Sequence, bytes2);
        return out.toByteArray();
    } catch (IOException ioe) {
        throw ioe;
    } catch (Exception e) {
        throw new IOException("Failed to encrypt" +
                " safe contents entry: " + e, e);
    }
}
 
Example 19
Source File: TestCipherKeyWrapperPBEKey.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
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 20
Source File: TestCipherKeyWrapperPBEKey.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
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;
        }
    }
}