List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec
public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
From source file:net.nicholaswilliams.java.licensing.encryption.Encryptor.java
private static SecretKey getSecretKey(char[] passphrase) { try {/*from www.jav a2 s. c o m*/ PBEKeySpec keySpec = new PBEKeySpec(passphrase, Encryptor.salt, Encryptor.iterationCount, Encryptor.aesKeyLength); byte[] shortKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec).getEncoded(); byte[] intermediaryKey = new byte[Encryptor.aesKeyLength / 8]; for (int i = 0, j = 0; i < Encryptor.aesKeyLength / 8; i++) { intermediaryKey[i] = shortKey[j]; if (++j == shortKey.length) j = 0; } return new SecretKeySpec(intermediaryKey, "AES"); } catch (NoSuchAlgorithmException e) { throw new AlgorithmNotSupportedException("DES with an MD5 Digest", e); } catch (InvalidKeySpecException e) { throw new InappropriateKeySpecificationException(e); } }
From source file:com.denel.facepatrol.MainActivity.java
private static SecretKey generateKey(char[] passphraseOrPin, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException { // Number of PBKDF2 hardening rounds to use. Larger values increase // computation time. You should select a value that causes computation // to take >100ms. final int iterations = 1000; // Generate a 256-bit key final int outputKeyLength = 256; SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations, outputKeyLength); SecretKey secretKey = secretKeyFactory.generateSecret(keySpec); return secretKey; }
From source file:com.microsoft.aad.adal.CordovaAdalPlugin.java
private SecretKey createSecretKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey tempkey = keyFactory .generateSecret(new PBEKeySpec(key.toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); return secretKey; }
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 {// w ww.java 2 s .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:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
@Override public boolean changePassphrase(String oldPassphrase, String newPassphrase) { SecretKeyFactory secretKeyFactory; File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME); File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW"); if (!headerFileNew.exists()) { try {/*w w w . j a v a2 s. co m*/ // Decrypt AES encryption key secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); // Create new vault nonce and salt byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt); // Create new key for AES key encryption SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey, newKeyFromPassphrase); } catch (Exception e) { Util.log("Error while reading or creating new vault header!"); return false; } } else { Util.log("New header file already exists. Cannot change passphrase!"); return false; } // Try to parse new header file try { FileInputStream headerInputStream = new FileInputStream(headerFileNew); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); headerFileNew.delete(); return false; } // Delete old header file and replace with new header file if (!headerFileOld.delete()) { headerFileNew.delete(); Util.log("Cannot delete old vault header!"); return false; } try { org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld); } catch (IOException e) { Util.log("Cannot replace old vault header!"); return false; } headerFileNew.delete(); return true; }
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java
/** * @param salt number of the key./*from ww w . j a v a2s .co m*/ * @return the CupherKey. * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ private Key getCiperKey(byte[] salt) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); // hashing the password 65K times takes 151ms, hashing 256 times takes 2ms. // Since the salt has 2^^72 values, 256 times is probably good enough. KeySpec spec = new PBEKeySpec(sharedKey.toCharArray(), salt, 256, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES"); return key; }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Encrypt private key with symmetric AES encryption, GCM mode mode and no padding * * @param privateKey byte64 encoded string representation of private key * @param keyPhrase key used for encryption, e.g. 12 random words * {@link EncryptionUtils#getRandomWords(int, Context)} * @return encrypted string, bytes first encoded base64, IV separated with "|", then to string *//* w w w . j av a 2 s . c o m*/ public static String encryptPrivateKey(String privateKey, String keyPhrase) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException { Cipher cipher = Cipher.getInstance(AES_CIPHER); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] salt = randomBytes(saltLength); KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength); SecretKey tmp = factory.generateSecret(spec); SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] bytes = encodeStringToBase64Bytes(privateKey); byte[] encrypted = cipher.doFinal(bytes); byte[] iv = cipher.getIV(); String encodedIV = encodeBytesToBase64String(iv); String encodedSalt = encodeBytesToBase64String(salt); String encodedEncryptedBytes = encodeBytesToBase64String(encrypted); return encodedEncryptedBytes + ivDelimiter + encodedIV + ivDelimiter + encodedSalt; }
From source file:com.owncloud.android.utils.EncryptionUtils.java
/** * Decrypt private key with symmetric AES encryption, GCM mode mode and no padding * * @param privateKey byte64 encoded string representation of private key, IV separated with "|" * @param keyPhrase key used for encryption, e.g. 12 random words * {@link EncryptionUtils#getRandomWords(int, Context)} * @return decrypted string/*from ww w . j av a2s.c o m*/ */ public static String decryptPrivateKey(String privateKey, String keyPhrase) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidKeySpecException, InvalidAlgorithmParameterException { // split up iv, salt String[] strings = privateKey.split(ivDelimiter); String realPrivateKey = strings[0]; byte[] iv = decodeStringToBase64Bytes(strings[1]); byte[] salt = decodeStringToBase64Bytes(strings[2]); Cipher cipher = Cipher.getInstance(AES_CIPHER); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength); SecretKey tmp = factory.generateSecret(spec); SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); byte[] bytes = decodeStringToBase64Bytes(realPrivateKey); byte[] decrypted = cipher.doFinal(bytes); String pemKey = decodeBase64BytesToString(decrypted); return pemKey.replaceAll("\n", "").replace("-----BEGIN PRIVATE KEY-----", "") .replace("-----END PRIVATE KEY-----", ""); }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private HashedDataType hashPbkd(ProtectedData<String> protectedData, String algorithmUri, String algorithmName) throws EncryptionException { char[] clearChars = getClearChars(protectedData); byte[] salt = generatePbkdSalt(); int iterations = getPbkdIterations(); SecretKeyFactory secretKeyFactory; try {/*from w w w . j av a 2s . c om*/ secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, iterations, getPbkdKeyLength()); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); HashedDataType hashedDataType = new HashedDataType(); DigestMethodType digestMethod = new DigestMethodType(); digestMethod.setAlgorithm(algorithmUri); digestMethod.setSalt(salt); digestMethod.setWorkFactor(iterations); hashedDataType.setDigestMethod(digestMethod); hashedDataType.setDigestValue(hashBytes); return hashedDataType; }
From source file:com.evolveum.midpoint.prism.crypto.ProtectorImpl.java
private boolean compareHashedPbkd(HashedDataType hashedDataType, String algorithmName, char[] clearChars) throws EncryptionException { DigestMethodType digestMethodType = hashedDataType.getDigestMethod(); byte[] salt = digestMethodType.getSalt(); Integer workFactor = digestMethodType.getWorkFactor(); byte[] digestValue = hashedDataType.getDigestValue(); int keyLen = digestValue.length * 8; SecretKeyFactory secretKeyFactory; try {/*from w w w. j av a2 s.co m*/ secretKeyFactory = SecretKeyFactory.getInstance(algorithmName); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e.getMessage(), e); } PBEKeySpec keySpec = new PBEKeySpec(clearChars, salt, workFactor, keyLen); SecretKey key; try { key = secretKeyFactory.generateSecret(keySpec); } catch (InvalidKeySpecException e) { throw new EncryptionException(e.getMessage(), e); } byte[] hashBytes = key.getEncoded(); return Arrays.equals(digestValue, hashBytes); }