List of usage examples for javax.crypto KeyGenerator generateKey
public final SecretKey generateKey()
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException { secureRandom = new SecureRandom(); this.vaultPath = vaultPath; this.encryptionMode = encryptionMode; File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME); if (!headerFile.exists()) { try {//w w w.j av a 2 s . co m KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(AES_KEY_SIZE_BIT); Key encryptionKey = keyGenerator.generateKey(); byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase); } catch (Exception e) { Util.log("Cannot create vault header!"); e.printStackTrace(); } } try { FileInputStream headerInputStream = new FileInputStream(headerFile); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); e.printStackTrace(); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); } catch (InvalidKeyException e) { throw new InvalidKeyException("Passphrase is wrong!"); } catch (Exception e) { Util.log("Cannot decrypt AES key"); e.printStackTrace(); } }
From source file:org.opensmartgridplatform.adapter.protocol.dlms.application.services.SecurityKeyService.java
/** * Generates a new key that can be used as DLMS master key, authentication * key, global unicast encryption key, M-Bus Default key or M-Bus User key. * <p>//from w w w. ja v a 2 s . co m * The master keys (DLMS master or M-Bus Default) cannot be changed on a * device, but can be generated for use in tests or with simulated devices. * * @return a new 16-byte AES key. */ public byte[] generateKey() { try { final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(AES_GMC_128_KEY_SIZE); return keyGenerator.generateKey().getEncoded(); } catch (final NoSuchAlgorithmException e) { throw new AssertionError("Expected AES algorithm to be available for key generation.", e); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testSoftwareRSAKeyWrapping() throws Exception { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); final SecretKey secretKey = keyGenerator.generateKey(); LOG.debug("secret key algo: " + secretKey.getAlgorithm()); final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, keyPair.getPublic()); LOG.debug("cipher security provider: " + cipher.getProvider().getName()); LOG.debug("cipher type: " + cipher.getClass().getName()); final byte[] wrappedKey = cipher.wrap(secretKey); cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate()); final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded()); }
From source file:org.cesecore.keys.util.KeyStoreTools.java
/** Generates symmetric keys in the Keystore token. * /*w ww.jav a2 s .c o m*/ * @param algorithm symmetric algorithm specified in http://download.oracle.com/javase/1.5.0/docs/api/index.html, suggest AES, DESede or DES * @param keysize keysize of symmetric key, suggest 128 or 256 for AES, 64 for 168 for DESede and 64 for DES * @param keyEntryName the alias the key will get in the keystore * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public void generateKey(final String algorithm, final int keysize, final String keyEntryName) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException { KeyGenerator generator = KeyGenerator.getInstance(algorithm, this.providerName); generator.init(keysize); Key key = generator.generateKey(); setKeyEntry(keyEntryName, key, null); }
From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java
/** * Set up the encryption context required for encrypting blobs. * @param metadata//from w ww. jav a 2 s . c om * Reference to blob metadata object that is used to set the encryption materials. * @param noPadding * Value indicating if the padding mode should be set or not. * @return The Cipher to use to decrypt the blob. * @throws StorageException * An exception representing any error which occurred during the operation. */ Cipher createAndSetEncryptionContext(Map<String, String> metadata, boolean noPadding) throws StorageException { Utility.assertNotNull("metadata", metadata); // The Key should be set on the policy for encryption. Otherwise, throw an error. if (this.keyWrapper == null) { throw new IllegalArgumentException(SR.KEY_MISSING); } try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(256); Cipher myAes; if (noPadding) { myAes = Cipher.getInstance("AES/CBC/NoPadding"); } else { myAes = Cipher.getInstance("AES/CBC/PKCS5Padding"); } SecretKey aesKey = keyGen.generateKey(); myAes.init(Cipher.ENCRYPT_MODE, aesKey); BlobEncryptionData encryptionData = new BlobEncryptionData(); encryptionData.setEncryptionAgent(new EncryptionAgent( Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1, EncryptionAlgorithm.AES_CBC_256)); // Wrap key Pair<byte[], String> encryptedKey = this.keyWrapper .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get(); encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(), encryptedKey.getKey(), encryptedKey.getValue())); encryptionData.setContentEncryptionIV(myAes.getIV()); metadata.put(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA, encryptionData.serialize()); return myAes; } catch (Exception e) { throw StorageException.translateClientException(e); } }
From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java
private boolean initialize() { try {//from ww w . j a v a 2 s. c o m encryptionReady = false; tokenRefreshRetryCount = TOKEN_REFRESH_RETRY_COUNT; if (Cipher.getMaxAllowedKeyLength("AES") < 256) { return setError(LxOfflineReason.INTERNAL_ERROR, "Enable Java cryptography unlimited strength (see binding doc)."); } // generate a random key for the session KeyGenerator aesKeyGen = KeyGenerator.getInstance("AES"); aesKeyGen.init(256); aesKey = aesKeyGen.generateKey(); // generate an initialization vector secureRandom = new SecureRandom(); secureRandom.nextBytes(initVector); IvParameterSpec ivSpec = new IvParameterSpec(initVector); // initialize aes cipher for command encryption aesEncryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesEncryptCipher.init(Cipher.ENCRYPT_MODE, aesKey, ivSpec); // initialize aes cipher for response decryption aesDecryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesDecryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivSpec); // get token value from configuration storage token = (String) configuration.get(SETTINGS_TOKEN); logger.debug("[{}] Retrieved token value: {}", debugId, token); } catch (InvalidParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "Invalid parameter: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES not supported on platform."); } catch (InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) { return setError(LxOfflineReason.INTERNAL_ERROR, "AES cipher initialization failed."); } return true; }
From source file:org.apache.hadoop.crypto.key.KeyProvider.java
/** * Generates a key material.// ww w . j a v a 2 s .c om * * @param size length of the key. * @param algorithm algorithm to use for generating the key. * @return the generated key. * @throws NoSuchAlgorithmException */ protected byte[] generateKey(int size, String algorithm) throws NoSuchAlgorithmException { algorithm = getAlgorithm(algorithm); KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm); keyGenerator.init(size); byte[] key = keyGenerator.generateKey().getEncoded(); return key; }
From source file:org.guanxi.idp.service.SSOBase.java
/** * Adds encrypted assertions to a SAML2 Response * * @param encryptionCert the X509 certificate to use for encrypting the assertions * @param assertionDoc the assertions to encrypt * @param responseDoc the SAML2 Response to add the encrypted assertions to * @throws GuanxiException if an error occurs *///from w w w .j a v a 2 s . c o m protected void addEncryptedAssertionsToResponse(X509Certificate encryptionCert, AssertionDocument assertionDoc, ResponseDocument responseDoc) throws GuanxiException { try { PublicKey keyEncryptKey = encryptionCert.getPublicKey(); // Generate a secret key KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); XMLCipher keyCipher = XMLCipher.getInstance(XMLCipher.RSA_OAEP); keyCipher.init(XMLCipher.WRAP_MODE, keyEncryptKey); Document domAssertionDoc = (Document) assertionDoc.newDomNode(xmlOptions); EncryptedKey encryptedKey = keyCipher.encryptKey(domAssertionDoc, secretKey); Element elementToEncrypt = domAssertionDoc.getDocumentElement(); XMLCipher xmlCipher = XMLCipher.getInstance(XMLCipher.AES_128); xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey); // Add KeyInfo to the EncryptedData element EncryptedData encryptedDataElement = xmlCipher.getEncryptedData(); KeyInfo keyInfo = new KeyInfo(domAssertionDoc); keyInfo.add(encryptedKey); encryptedDataElement.setKeyInfo(keyInfo); // Encrypt the assertion xmlCipher.doFinal(domAssertionDoc, elementToEncrypt, false); // Go back into XMLBeans land... EncryptedDataDocument encryptedDataDoc = EncryptedDataDocument.Factory.parse(domAssertionDoc); // ...and add the encrypted assertion to the response responseDoc.getResponse().addNewEncryptedAssertion() .setEncryptedData(encryptedDataDoc.getEncryptedData()); // Look for the Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey node... EncryptedDataType encryptedData = responseDoc.getResponse().getEncryptedAssertionArray(0) .getEncryptedData(); NodeList nodes = encryptedData.getKeyInfo().getDomNode().getChildNodes(); Node encryptedKeyNode = null; for (int c = 0; c < nodes.getLength(); c++) { encryptedKeyNode = nodes.item(c); if (encryptedKeyNode.getLocalName() != null) { if (encryptedKeyNode.getLocalName().equals("EncryptedKey")) break; } } // ...get a new KeyInfo ready... KeyInfoDocument keyInfoDoc = KeyInfoDocument.Factory.newInstance(); X509DataType x509Data = keyInfoDoc.addNewKeyInfo().addNewX509Data(); // ...and a useable version of the SP's encryption certificate... StringWriter sw = new StringWriter(); PEMWriter pemWriter = new PEMWriter(sw); pemWriter.writeObject(encryptionCert); pemWriter.close(); String x509 = sw.toString(); x509 = x509.replaceAll("-----BEGIN CERTIFICATE-----", ""); x509 = x509.replaceAll("-----END CERTIFICATE-----", ""); // ...add the encryption cert to the new KeyInfo... x509Data.addNewX509Certificate().setStringValue(x509); // ...and insert it into Response/EncryptedAssertion/EncryptedData/KeyInfo/EncryptedKey encryptedKeyNode.appendChild( encryptedKeyNode.getOwnerDocument().importNode(keyInfoDoc.getKeyInfo().getDomNode(), true)); } catch (NoSuchAlgorithmException nsae) { logger.error("AES encryption not available"); throw new GuanxiException(nsae); } catch (XMLEncryptionException xea) { logger.error("RSA_OAEP error with WRAP_MODE"); throw new GuanxiException(xea); } catch (Exception e) { logger.error("Error encyrpting the assertion"); throw new GuanxiException(e); } }
From source file:com.z299studio.pb.FingerprintDialog.java
private void initCipher(int mode) { try {//from ww w. j a v a2 s . c o m IvParameterSpec ivParams; KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey key; mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (mode == Cipher.ENCRYPT_MODE) { KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); mCipher.init(mode, keyGenerator.generateKey()); } else { key = (SecretKey) keyStore.getKey(KEY_NAME, null); ivParams = new IvParameterSpec(Application.getInstance().getFpIv()); mCipher.init(mode, key, ivParams); } mCryptoObject = new FingerprintManager.CryptoObject(mCipher); } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { Log.e("Pb:FingerprintDialog", "Runtime error in initCipher."); Log.e("Pb:FingerprintDialog", e.toString()); } }
From source file:org.apache.ws.security.message.EncryptionTest.java
/** * Setup method//from w w w . j a v a 2 s. c o m * * @throws java.lang.Exception Thrown when there is a problem in setup */ @org.junit.Before public void setUp() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); key = keyGen.generateKey(); keyData = key.getEncoded(); WSSConfig wssConfig = WSSConfig.getNewInstance(); wssConfig.setWsiBSPCompliant(true); secEngine.setWssConfig(wssConfig); }