List of usage examples for javax.crypto SecretKeyFactory generateSecret
public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException
From source file:test.frames.CryptoServiceSingleton.java
/** * Generate the AES key from the salt and the private key. * * @param salt the salt (hexadecimal) * @param privateKey the private key/*w w w . j a v a2 s .com*/ * @return the generated key. */ private SecretKey generateAESKey(String privateKey, String salt) { try { byte[] raw = Hex.decodeHex(salt.toCharArray()); KeySpec spec = new PBEKeySpec(privateKey.toCharArray(), raw, iterationCount, keySize); SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF_2_WITH_HMAC_SHA_1); return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), AES_ECB_ALGORITHM); } catch (DecoderException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } catch (InvalidKeySpecException e) { throw new IllegalStateException(e); } }
From source file:TDS.Shared.Web.Encryption.java
/** * initializes ciphers and adds jce provider if provided * //from w w w . ja v a 2s . c o m * @throws TDSEncryptionException */ @PostConstruct protected void init() { final String encryptionKey = configurationManager.getAppSettings().get("EncryptionKey"); if (encryptionKey == null || StringUtils.isBlank(encryptionKey) || encryptionKey.length() < MINIMUM_KEY_LENGTH) { throw new TDSEncryptionException( String.format("Number of characters for key must be greater than %s", MINIMUM_KEY_LENGTH)); } if (_jceProvider != null) { try { Security.addProvider(((Provider) Class.forName(_jceProviderClass).newInstance())); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { _logger.error(e.getMessage(), e); throw new TDSEncryptionException("JCE Provider class name is not valid"); } } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBE_KEY_ALGORITHM); KeySpec keySpec = new PBEKeySpec(encryptionKey.toCharArray(), PBE_SALT, PBE_NUM_ITERATIONS, PBE_KEY_LENGTH); SecretKey secretKeyTemp; secretKeyTemp = secretKeyFactory.generateSecret(keySpec); _secretKey = new SecretKeySpec(secretKeyTemp.getEncoded(), CIPHER_ALGORITHM); if (_jceProvider == null) { _encryptCipher = Cipher.getInstance(TRANSFORMATION); _decryptCipher = Cipher.getInstance(TRANSFORMATION); } else { _encryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider); _decryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider); } _encryptCipher.init(Cipher.ENCRYPT_MODE, _secretKey); } catch (NoSuchAlgorithmException e) { _logger.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Algorithm is not available"); } catch (InvalidKeySpecException e) { _logger.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Key specification is not valid"); } catch (NoSuchPaddingException e) { _logger.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Padding is not valid"); } catch (NoSuchProviderException e) { _logger.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Provider is not available"); } catch (InvalidKeyException e) { _logger.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Key is not valid"); } }
From source file:mitm.common.security.crypto.PBDecryptionInputStream.java
private void init(String algorithm, byte[] salt, int iterationCount) throws CryptoException { try {//from w w w . j ava 2 s . c o m SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecretKeyFactory keyFactory = securityFactory.createSecretKeyFactory(algorithm); PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount); /* * Clear out the password */ Arrays.fill(password, '#'); Key secretKey = keyFactory.generateSecret(keySpec); cipher = securityFactory.createCipher(algorithm); cipher.init(Cipher.DECRYPT_MODE, secretKey); } catch (NoSuchProviderException e) { throw new NoSuchProviderRuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } catch (InvalidKeySpecException e) { throw new CryptoException(e); } catch (NoSuchPaddingException e) { throw new CryptoException(e); } catch (InvalidKeyException e) { throw new CryptoException(e); } }
From source file:org.jets3t.service.security.EncryptionUtil.java
/** * Constructs class configured with the provided password, and set up to use the encryption * method specified.//from w w w . j a va 2s .c om * * @param encryptionKey * the password to use for encryption/decryption. * @param algorithm * the Java name of an encryption algorithm to use, eg PBEWithMD5AndDES * @param version * the version of encyption to use, for historic and future compatibility. * Unless using an historic version, this should always be * {@link #DEFAULT_VERSION} * * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeySpecException */ public EncryptionUtil(String encryptionKey, String algorithm, String version) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException { this.algorithm = algorithm; this.version = version; if (log.isDebugEnabled()) { log.debug("Cryptographic properties: algorithm=" + this.algorithm + ", version=" + this.version); } if (!DEFAULT_VERSION.equals(version)) { throw new RuntimeException("Unrecognised crypto version setting: " + version); } PBEKeySpec keyspec = new PBEKeySpec(encryptionKey.toCharArray(), salt, ITERATION_COUNT, 32); SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm); key = skf.generateSecret(keyspec); algParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT); }
From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java
public AAAEncryptionServiceImpl(AaaEncryptServiceConfig encrySrvConfig, final DataBroker dataBroker) { SecretKey tempKey = null;//ww w . j a v a2s . co m IvParameterSpec tempIvSpec = null; if (encrySrvConfig.getEncryptSalt() == null) { throw new IllegalArgumentException( "null encryptSalt in AaaEncryptServiceConfig: " + encrySrvConfig.toString()); } if (encrySrvConfig.getEncryptKey() != null && encrySrvConfig.getEncryptKey().isEmpty()) { LOG.debug("Set the Encryption service password and encrypt salt"); String newPwd = RandomStringUtils.random(encrySrvConfig.getPasswordLength(), true, true); final Random random = new SecureRandom(); byte[] salt = new byte[16]; random.nextBytes(salt); String encodedSalt = Base64.getEncoder().encodeToString(salt); encrySrvConfig = new AaaEncryptServiceConfigBuilder(encrySrvConfig).setEncryptKey(newPwd) .setEncryptSalt(encodedSalt).build(); updateEncrySrvConfig(newPwd, encodedSalt); initializeConfigDataTree(encrySrvConfig, dataBroker); } final byte[] enryptionKeySalt = Base64.getDecoder().decode(encrySrvConfig.getEncryptSalt()); try { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encrySrvConfig.getEncryptMethod()); final KeySpec spec = new PBEKeySpec(encrySrvConfig.getEncryptKey().toCharArray(), enryptionKeySalt, encrySrvConfig.getEncryptIterationCount(), encrySrvConfig.getEncryptKeyLength()); tempKey = keyFactory.generateSecret(spec); tempKey = new SecretKeySpec(tempKey.getEncoded(), encrySrvConfig.getEncryptType()); tempIvSpec = new IvParameterSpec(enryptionKeySalt); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { LOG.error("Failed to initialize secret key", e); } key = tempKey; ivspec = tempIvSpec; Cipher cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.ENCRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create encrypt cipher.", e); } this.encryptCipher = cipher; cipher = null; try { cipher = Cipher.getInstance(encrySrvConfig.getCipherTransforms()); cipher.init(Cipher.DECRYPT_MODE, key, ivspec); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { LOG.error("Failed to create decrypt cipher.", e); } this.decryptCipher = cipher; }
From source file:csh.cryptonite.Cryptonite.java
public static String decrypt(String value, Context context) throws RuntimeException { try {/*from w ww. j a v a 2 s.co m*/ final byte[] bytes = value != null ? Base64.decode(value, Base64.DEFAULT) : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(jniFullPw().toCharArray())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"), 20)); return new String(pbeCipher.doFinal(bytes), "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:csh.cryptonite.Cryptonite.java
public static String encrypt(String value, Context context) throws RuntimeException { try {/*from w w w . ja v a 2s . c o m*/ final byte[] bytes = value != null ? value.getBytes("utf-8") : new byte[0]; SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(jniFullPw().toCharArray())); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"), 20)); return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP), "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } }
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 {/* www .j a v a2s .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:net.sourceforge.jencrypt.lib.CryptoWrapper.java
private byte[] getHashedPassword(CryptoWrapperBuilder builder) throws NoSuchAlgorithmException, InvalidKeySpecException { /* Apply PBKDF2 (Password-Based Key Derivation Function 2) with * HMAC-SHA-1 to the password (for further details, see RFC-2898). *///w ww . ja va 2s. co m SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(builder.password.toCharArray(), salt, keyDerivationIterationCount, builder.keySize); SecretKey secret = factory.generateSecret(spec); return secret.getEncoded(); }
From source file:org.mxupdate.eclipse.properties.ProjectProperties.java
/** * Returns encrypted/decrypted by salt password. Uses SHA-1 Message Digest * Algorithm as defined in NIST's FIPS 180-1. The output of this algorithm * is a 160-bit digest./*from w ww . j av a 2 s . co m*/ * * @param _password password to encrypt / decrypt * @param _decrypt <i>true</i> to decrypt or <i>false</i> to encrypt * @return decrypted / encrypted by salt password * @see #PDE_ALGORITHM * @see #PDE_PASSWORD * @see #PDE_SALT * @see #PDE_ITERATION */ private String decryptEncrypt(final String _password, final boolean _decrypt) { String ret = null; if (_password != null) { try { // create PBE parameter set final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(ProjectProperties.PDE_SALT, ProjectProperties.PDE_ITERATION); final PBEKeySpec pbeKeySpec = new PBEKeySpec(ProjectProperties.PDE_PASSWORD, ProjectProperties.PDE_SALT, ProjectProperties.PDE_ITERATION); final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ProjectProperties.PDE_ALGORITHM); final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); final Cipher cipher = Cipher.getInstance(pbeKey.getAlgorithm()); if (_decrypt) { cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); // decode base64 to get bytes final byte[] dec = Base64.decodeBase64(_password.getBytes(ProjectProperties.ENCODING)); // decrypt final byte[] ciphertext = cipher.doFinal(dec); ret = new String(ciphertext, ProjectProperties.ENCODING); } else { cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); final byte[] pwdText = _password.getBytes(ProjectProperties.ENCODING); // encrypt the cleartext final byte[] ciphertext = cipher.doFinal(pwdText); ret = new String(Base64.encodeBase64(ciphertext), ProjectProperties.ENCODING); } } catch (final Exception e) { throw new Error(e); } } return ret; }