List of usage examples for javax.crypto SecretKeyFactory generateSecret
public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException
From source file:com.diona.fileReader.CipherUtil.java
/** * Generates the secret key to be used for encryption. The secret key is retrieved from the shared preferences if * previously calculated.//from w ww. j a va2 s . c o m * * @return A new secret key if not previously calculated. * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws UnsupportedEncodingException */ private SecretKeySpec getSecretKey(final Context context) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException { // final SocialWorkerSharedPreferences sharedPreferences = SocialWorkerSharedPreferences.getInstance(); // if (sharedPreferences.getSecretKey() == null) { final byte[] salt = generateRandomKeyBytes(SALT_LENGTH); final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); final PBEKeySpec spec = new PBEKeySpec(SECRET_KEY_PASSPHRASE.toCharArray(), salt, KEY_ITERATIONS, KEY_SIZE); final SecretKey secretKey = factory.generateSecret(spec); final SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), ENCRYPTION_ALGORITHM); // Set the value of the secret key in private shared preferences //sharedPreferences.setSecretKey(secretKeySpec); return secretKeySpec; /*} else { return sharedPreferences.getSecretKey(); }*/ }
From source file:org.wisdom.crypto.CryptoServiceSingleton.java
/** * Generate the AES key from the salt and the private key. * * @param salt the salt (hexadecimal) * @param privateKey the private key//from w w w . j a va 2 s . c o m * @return the generated key. */ private SecretKey generateAESKey(String privateKey, String salt) { try { byte[] raw = decodeHex(salt); 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 (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new IllegalStateException(e); } }
From source file:mitm.common.security.crypto.PBEncryptionOutputStream.java
private void init() throws CryptoException { try {//from w ww. j a v a 2 s.c o m SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); SecretKeyFactory keyFactory = securityFactory.createSecretKeyFactory(algorithm); RandomGenerator randomGenerator = securityFactory.createRandomGenerator(); salt = randomGenerator.generateRandom(saltLength); 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.ENCRYPT_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:ch.bfh.evoting.alljoyn.MessageEncrypter.java
/** * Key derivation method from the given password * @param password password to derive//from ww w .j ava2 s.com */ private void derivateKey(char[] password) { //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption SecretKeyFactory factory; try { factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); //1000 iteration should be enough since the attack has to be done online and //salt changes for each group KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256); SecretKey tmp = factory.generateSecret(spec); secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); this.isReady = true; } catch (NoSuchAlgorithmException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } catch (InvalidKeySpecException e) { Log.d(TAG, e.getMessage() + " "); e.printStackTrace(); } }
From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java
private String authenticate(String user, String password, ServerConfig serverConfig, boolean checkAge, int authTypeId) throws Exception { String selectSQL = ""; try {/*from w ww . j av a 2s.c o m*/ if (serverConfig == null) { log.error("ServerConfig is null."); return "-3"; } int idx = user.indexOf("_"); if (idx != -1) { // let bots through String idStr = user.substring(idx + 1); // if (user.toUpperCase().startsWith("BOT")) { if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.debug("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(idStr, idStr, "UNUSED", new Long(0), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), (serverConfig.getInitialAmount().multiply(new BigDecimal(20))), true, false, 0); return String.valueOf(userId); } else { return idStr; } // } } if (user.toUpperCase().startsWith("GUESTXDEMO")) { return String.valueOf(pid.incrementAndGet()); } log.debug("loading class name " + jdbcDriverClassName); // This will load the MySQL driver, each DB has its own driver // "com.mysql.jdbc.Driver" Class.forName(jdbcDriverClassName); // Setup the connection with the DB // "jdbc:mysql://localhost/dbName?" + "user=&password="); connect = DriverManager.getConnection(connectionStr); // Statements allow to issue SQL queries to the database statement = connect.createStatement(); log.debug("Execute query: authenticate"); selectSQL = "select id, username, password, salt from " + dbPrefix + "users" + " where username = " + "\'" + user + "\'"; log.debug("Executing query : " + selectSQL); resultSet = statement.executeQuery(selectSQL); String members_pass_hash = null; String members_pass_salt = null; String members_display_name = null; boolean authenticated = false; int member_id = 0; int posts = 0; if (resultSet != null && resultSet.next()) { String members_seo_name = resultSet.getString("username"); member_id = resultSet.getInt("id"); members_display_name = resultSet.getString("username"); members_pass_hash = resultSet.getString("password"); members_pass_salt = resultSet.getString("salt"); log.error("DB members_pass_hash = " + members_pass_hash); // posts = resultSet.getInt("user_posts"); // log.debug("# of Post " + posts); log.debug("User: " + user + " Password " + "********"); Verifier verifier = new Verifier(); PasswordResponse response = new PasswordResponse(); response.setAlgorithm(Algorithm.PBKDF2); response.setSalt(members_pass_salt); response.setAlgorithmDetails(new AlgorithmDetails()); response.getAlgorithmDetails().setIterations(1000); response.getAlgorithmDetails().setHashFunction("SHA256"); response.getAlgorithmDetails().setKeySize(263); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), members_pass_salt.getBytes(), 1000, response.getAlgorithmDetails().getKeySize()); SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory( "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", "")); byte[] hash = skf.generateSecret(spec).getEncoded(); String encodedHash = Base64.encodeBase64String(hash); response.setHash(encodedHash); log.debug("Encrypted hash " + response.getHash()); if (verifier.verify(password, response)) { // Check it against database stored hash authenticated = encodedHash.equals(members_pass_hash) ? true : false; } else { log.debug("failed verification of hashing"); } if (authenticated) { log.debug("Authentication successful"); log.debug("Member id " + String.valueOf(member_id)); if (serverConfig.isUseIntegrations()) { WalletAdapter walletAdapter = new WalletAdapter(); log.error("Calling createWalletAccount"); //walletAdapter.createWalletAccount(new Long(String.valueOf(member_id))); Long userId = walletAdapter.checkCreateNewUser(String.valueOf(member_id), members_seo_name, "UNUSED", new Long(1), serverConfig.getCurrency(), serverConfig.getWalletBankAccountId(), serverConfig.getInitialAmount(), checkAge, needAgeAgreement, authTypeId); if (userId < 0) { // user did not accept age clauses return "-5"; } log.debug("assigned new id as #" + String.valueOf(userId)); return String.valueOf(userId); } else { return String.valueOf(member_id); } /* if (posts >= 1) { return String.valueOf(member_id); } else { log.error("Required number of posts not met, denied login"); return "-2"; }*/ } else { log.error("hash not matched for user " + user + " password " + password); return "-1"; } } else { log.error("resultset is null " + selectSQL); } } catch (Exception e) { log.error("Error : " + e.toString()); // throw e; } finally { close(); } return "-3"; }
From source file:org.securityfilter.authenticator.persistent.DefaultPersistentLoginManager.java
/** * Set the Encryptin Key used to create a secret key, the secret key is passed * to the Cipher object to be used during encryption and decryption of cookie * values./* w ww. jav a 2 s . c o m*/ * <p> * <i>NOTE: This entry in the config file must NOT appear before any of the other * encryption config entries</i> * * @param encryptionkey A String containing the encryption key as * defined in config file. This is a required * config entry if protection is set to ALL or ENCRYPTION. */ public void setEncryptionKey(String encryptionkey) { this.encryptionKey = encryptionkey; try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm); byte[] desKeyData = encryptionkey.getBytes(); DESKeySpec desKeySpec = new DESKeySpec(desKeyData); secretKey = keyFactory.generateSecret(desKeySpec); } catch (Exception e) { System.out.println("Error: " + e); e.printStackTrace(); } }
From source file:org.kawanfw.commons.util.convert.Pbe.java
/** * Encrypt or decrypt a string using a password * /* w w w. jav a 2s. c o m*/ * @param mode * Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE * @param in * the string to encrypt or Decrypt. if to decrypt: string must * be Hex encoded * @param password * the password to use * @return if Cipher.ENCRYPT_MODE: the encrypted string in hexadecimal if * Cipher.DECRYPT_MODE: the decrypted string in clear readable * format * * @throws Exception */ private String cipher(int mode, String in, char[] password) throws Exception { if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) { throw new IllegalArgumentException("mode is not Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE!"); } if (in == null) { throw new IllegalArgumentException("in string can not be null!"); } if (password == null) { throw new IllegalArgumentException("password can not be null!"); } PBEKeySpec pbeKeySpec; PBEParameterSpec pbeParamSpec; SecretKeyFactory keyFac; // Salt byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; // Iteration count int count = 20; // Create PBE parameter set pbeParamSpec = new PBEParameterSpec(salt, count); pbeKeySpec = new PBEKeySpec(password); keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); // Create PBE Cipher Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); // Initialize PBE Cipher with key and parameters pbeCipher.init(mode, pbeKey, pbeParamSpec); // Our cleartext byte[] inText = null; if (mode == Cipher.ENCRYPT_MODE) { inText = in.getBytes(); } else { inText = CodecHex.decodeHex(in.toCharArray()); } // Encrypt the cleartext byte[] ciphertext = pbeCipher.doFinal(inText); if (mode == Cipher.ENCRYPT_MODE) { return new String(CodecHex.encodeHex(ciphertext)); } else { return new String(ciphertext); } }
From source file:org.kawanfw.commons.util.convert.Pbe.java
/** * Encrypt or decrypt a file using a password * //from ww w. j a v a 2 s . com * @param mode * Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE * @param fileIn * the file to encrypt or Decrypt. * @param fileOut * the resulting encrypted/decrypted file * @param password * the password to use * * @throws Exception */ private void cipher(int mode, File fileIn, File fileOut, char[] password) throws Exception { if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) { throw new IllegalArgumentException("mode is not Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE!"); } if (fileIn == null) { throw new IllegalArgumentException("in File can not be null!"); } if (fileOut == null) { throw new IllegalArgumentException("out File can not be null!"); } if (password == null) { throw new IllegalArgumentException("password can not be null!"); } PBEKeySpec pbeKeySpec; PBEParameterSpec pbeParamSpec; SecretKeyFactory keyFac; // Salt byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; // Iteration count int count = 1; // Create PBE parameter set pbeParamSpec = new PBEParameterSpec(salt, count); pbeKeySpec = new PBEKeySpec(password); keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); // Create PBE Cipher Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); // Initialize PBE Cipher with key and parameters pbeCipher.init(mode, pbeKey, pbeParamSpec); InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(fileIn)); out = new BufferedOutputStream(new FileOutputStream(fileOut)); byte[] input = new byte[2048 * 10]; int bytesRead; while ((bytesRead = in.read(input)) != -1) { byte[] output = pbeCipher.update(input, 0, bytesRead); if (output != null) out.write(output); } byte[] output = pbeCipher.doFinal(); if (output != null) out.write(output); out.flush(); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java
/** * Generates an AES key from the password using PBKDF2. * * @param salt the salt//w w w.jav a2 s. c o m */ protected Key generateSecretKey(byte[] salt) throws GeneralSecurityException { char[] password = getPassword(); SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1); PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH); clearPassword(password); Key derived = factory.generateSecret(spec); spec.clearPassword(); return new SecretKeySpec(derived.getEncoded(), AES); }
From source file:org.fuin.utils4j.Utils4J.java
/** * Creates a cipher for encryption or decryption. * /*from w ww.j ava 2 s. c om*/ * @param algorithm * PBE algorithm like "PBEWithMD5AndDES" or * "PBEWithMD5AndTripleDES". * @param mode * Encyrption or decyrption. * @param password * Password. * @param salt * Salt usable with algorithm. * @param count * Iterations. * * @return Ready initialized cipher. * * @throws GeneralSecurityException * Error creating the cipher. */ private static Cipher createCipher(final String algorithm, final int mode, final char[] password, final byte[] salt, final int count) throws GeneralSecurityException { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm); final PBEKeySpec keySpec = new PBEKeySpec(password); final SecretKey key = keyFactory.generateSecret(keySpec); final Cipher cipher = Cipher.getInstance(algorithm); final PBEParameterSpec params = new PBEParameterSpec(salt, count); cipher.init(mode, key, params); return cipher; }