Search in sources :

Example 41 with KeyGenerator

use of javax.crypto.KeyGenerator in project camel by apache.

the class EncryptionAlgorithmTest method testTRIPLEDES.

@Test
public void testTRIPLEDES() throws Exception {
    // Set up the Key
    KeyGenerator keygen = KeyGenerator.getInstance("DESede");
    keygen.init(192);
    SecretKey key = keygen.generateKey();
    final XMLSecurityDataFormat xmlEncDataFormat = new XMLSecurityDataFormat();
    xmlEncDataFormat.setPassPhrase(key.getEncoded());
    xmlEncDataFormat.setSecureTagContents(true);
    xmlEncDataFormat.setSecureTag("//cheesesites/italy/cheese");
    xmlEncDataFormat.setXmlCipherAlgorithm(XMLCipher.TRIPLEDES);
    context.addRoutes(new RouteBuilder() {

        public void configure() {
            from("direct:start").marshal(xmlEncDataFormat).to("mock:encrypted").log("Body: + ${body}").unmarshal(xmlEncDataFormat).to("mock:decrypted");
        }
    });
    xmlsecTestHelper.testDecryption(context);
}
Also used : SecretKey(javax.crypto.SecretKey) RouteBuilder(org.apache.camel.builder.RouteBuilder) KeyGenerator(javax.crypto.KeyGenerator) Test(org.junit.Test)

Example 42 with KeyGenerator

use of javax.crypto.KeyGenerator in project keywhiz by square.

the class GenerateAesKeyCommand method generate.

@VisibleForTesting
static void generate(char[] password, Path destination, int keySize, String alias, SecureRandom random) throws Exception {
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(keySize, random);
    SecretKey key = generator.generateKey();
    KeyStore keyStore = KeyStore.getInstance("JCEKS");
    // KeyStores must be initialized before use.
    keyStore.load(null);
    keyStore.setKeyEntry(alias, key, password, null);
    try (OutputStream out = Files.newOutputStream(destination)) {
        keyStore.store(out, password);
    }
}
Also used : SecretKey(javax.crypto.SecretKey) OutputStream(java.io.OutputStream) KeyGenerator(javax.crypto.KeyGenerator) KeyStore(java.security.KeyStore) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 43 with KeyGenerator

use of javax.crypto.KeyGenerator in project nhin-d by DirectProject.

the class PKCS11SecretKeyManager method addAESKey.

private void addAESKey() {
    final String input = JOptionPane.showInputDialog(this, "Key Alias Name:", "Generate New random AES Secret Key", JOptionPane.OK_CANCEL_OPTION);
    if (input != null && !input.trim().isEmpty()) {
        // generate a new random secret key
        try {
            final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            // cryptograph. secure random 
            final SecureRandom random = new SecureRandom();
            keyGen.init(random);
            final SecretKey key = keyGen.generateKey();
            mgr.clearKey(input);
            mgr.setKey(input, key);
            updateKeyTableData();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Failed to add random new AES key: " + e.getMessage(), "Add Key Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}
Also used : SecretKey(javax.crypto.SecretKey) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) CryptoException(org.nhindirect.common.crypto.exceptions.CryptoException)

Example 44 with KeyGenerator

use of javax.crypto.KeyGenerator in project nhin-d by DirectProject.

the class PKCS11Commands method importPrivateKeyFile.

//@Command(name = "ImportP12FileForTempKey", usage = IMPORT_P12_FILE_FOR_TEMP_KEY)
public void importPrivateKeyFile(String[] args) {
    if (!(mgr instanceof WrappableKeyProtectionManager)) {
        System.out.println("Key store manager does not support wrapping.");
        return;
    }
    final WrappableKeyProtectionManager wrapMgr = (WrappableKeyProtectionManager) mgr;
    final String fileName = StringArrayUtil.getRequiredValue(args, 0);
    final String keyStorePass = StringArrayUtil.getOptionalValue(args, 1, "");
    final String privKeyPass = StringArrayUtil.getOptionalValue(args, 2, "");
    try {
        final KeyStore pkcs11Store = mgr.getKS();
        final String providerName = pkcs11Store.getProvider().getName();
        System.out.println("Provider Name: " + providerName);
        /*
			 * 1. Create an AES128 secret key on the HSM that will be used to 
			 * encrypt and decrypt private key data.  Use the PrivKeyProtKey entry to store it
			 */
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES", providerName);
        keyGen.init(128);
        final SecretKey keyStoreSecretKey = keyGen.generateKey();
        /*
			 * 2. Get an existing private key that was generated and is stored in a p12 file.  
			 * For real operations, the private key may be generated on an HSM and exported in wrapped format for
			 * storage in a database.  For this test, we'll just use an existing private key in a p12 file and 
			 * wrap it on the HSM.
			 */
        final KeyStore store = KeyStore.getInstance("pkcs12");
        store.load(FileUtils.openInputStream(new File(fileName)), keyStorePass.toCharArray());
        // there should only be on entry
        final String alias = store.aliases().nextElement();
        final PrivateKey entry = (PrivateKey) store.getKey(alias, privKeyPass.toCharArray());
        /*
			 * 3. "Wrap" the private using secret key and AES128 encryption and write it to a file.  The encryption is done
			 * on the HSM so the secret key never leaves the HSM token.  We aren't actually "wrapping" the private key because
			 * it's not on the HSM.  Using "encrypt" instead.
			 */
        /*
			final Cipher wrapCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", providerName);
			wrapCipher.init(Cipher.WRAP_MODE, keyStoreSecretKey, iv);
			byte[] wrappedKey = wrapCipher.wrap(entry);
			*/
        byte[] wrappedKey = wrapMgr.wrapWithSecretKey(keyStoreSecretKey, entry);
        /*
			 * 4. Now we have a wrap key in a file.  Let's install it into the token using the 
			 * secret key on the HSM.  This should return us with a private key object, but we should
			 * not be able to get access to the actual unencrypted key data.
			 */
        byte[] encryptedKey = wrappedKey;
        /*
			final Cipher unwrapCipher = Cipher.getInstance("AES/CBC/PKCS5Padding", providerName);
			unwrapCipher.init(Cipher.UNWRAP_MODE, keyStoreSecretKey, iv);
			@SuppressWarnings("unused")
			final PrivateKey securedPrivateKey = (PrivateKey)unwrapCipher.unwrap(encryptedKey, "RSA", Cipher.PRIVATE_KEY);
			*/
        @SuppressWarnings("unused") final PrivateKey securedPrivateKey = (PrivateKey) wrapMgr.unwrapWithSecretKey(keyStoreSecretKey, encryptedKey, "RSA", Cipher.PRIVATE_KEY);
        System.out.println("Successfully created an unwrapped private key");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : WrappableKeyProtectionManager(org.nhindirect.common.crypto.WrappableKeyProtectionManager) SecretKey(javax.crypto.SecretKey) PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) KeyGenerator(javax.crypto.KeyGenerator) File(java.io.File)

Example 45 with KeyGenerator

use of javax.crypto.KeyGenerator in project nhin-d by DirectProject.

the class PKCS11Commands method addRandomSecretKey.

@Command(name = "CreateRandomSecretKey", usage = ADD_RANDOM_SECRET_KEY)
public void addRandomSecretKey(String[] args) {
    final String keyName = StringArrayUtil.getRequiredValue(args, 0);
    // generate a new random secret key
    try {
        final KeyGenerator keyGen = KeyGenerator.getInstance("AES", mgr.getKS().getProvider().getName());
        keyGen.init(128);
        final SecretKey key = keyGen.generateKey();
        mgr.clearKey(keyName);
        mgr.setKey(keyName, key);
    } catch (Exception e) {
        System.err.println("Failed to add new random secret key: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : SecretKey(javax.crypto.SecretKey) KeyGenerator(javax.crypto.KeyGenerator) Command(org.nhindirect.common.tooling.Command)

Aggregations

KeyGenerator (javax.crypto.KeyGenerator)166 SecretKey (javax.crypto.SecretKey)117 SecureRandom (java.security.SecureRandom)53 Cipher (javax.crypto.Cipher)43 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)32 Key (java.security.Key)31 Test (org.junit.Test)25 InvalidKeyException (java.security.InvalidKeyException)19 IvParameterSpec (javax.crypto.spec.IvParameterSpec)19 IOException (java.io.IOException)18 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)13 BadPaddingException (javax.crypto.BadPaddingException)13 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)13 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)13 File (java.io.File)12 FileOutputStream (java.io.FileOutputStream)12 RouteBuilder (org.apache.camel.builder.RouteBuilder)12 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)11 Provider (java.security.Provider)11 SecretKeySpec (javax.crypto.spec.SecretKeySpec)10