List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec
public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
From source file:components.security.Password.java
/** * Hashes the password using pbkdf2 and the given salt. * * @param password the plain text password to hash. * @param salt the salt for the password * @return the hashed password//ww w .ja v a 2 s. c o m */ public char[] hash(char[] password, byte[] salt) { checkNotNull(password); checkArgument(password.length != 0); checkNotNull(salt); checkArgument(salt.length != 0); try { SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey key = f.generateSecret(new PBEKeySpec(password, salt, iterations, desiredKeyLenght)); return Base64.encodeBase64String(key.getEncoded()).toCharArray(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { Logger.error("Problem during password hashing", e); throw new IllegalStateException("Could not hash the password of the user.", e); } }
From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java
/** * Method to initialize the cipher object with the correct encryption algorithm. * * @throws Exception//from w ww . j a va 2 s . c om */ protected void initializeCipher() throws Exception { SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY); KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128); SecretKey tmp = factory.generateSecret(spec); if (log.isDebugEnabled()) log.debug("Secret Key Length: " + tmp.getEncoded().length); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector)); }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility * is required but encryption (obfuscation, technically) is required. * * @param value - The plain text data to encrypt * @param salt - The salt value to utilize for the request * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory * @param iterations - The number of times to loop through the keyspec * @param keyBits - The size of the key, in bits * @param algorithm - The algorithm to encrypt the data with * @param cipherInstance - The cipher instance to utilize * @param encoding - The text encoding// w ww.j av a 2s . c o m * @return The encrypted string in a reversible format * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final String encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", secretInstance); DEBUGGER.debug("Value: {}", iterations); DEBUGGER.debug("Value: {}", keyBits); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", cipherInstance); DEBUGGER.debug("Value: {}", encoding); } String encPass = null; try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance); PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits); SecretKey keyTmp = keyFactory.generateSecret(keySpec); SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm); Cipher pbeCipher = Cipher.getInstance(cipherInstance); pbeCipher.init(Cipher.ENCRYPT_MODE, sks); AlgorithmParameters parameters = pbeCipher.getParameters(); IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class); byte[] cryptoText = pbeCipher.doFinal(value.getBytes(encoding)); byte[] iv = ivParameterSpec.getIV(); String combined = Base64.getEncoder().encodeToString(iv) + ":" + Base64.getEncoder().encodeToString(cryptoText); encPass = Base64.getEncoder().encodeToString(combined.getBytes()); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } catch (NoSuchPaddingException npx) { throw new SecurityException(npx.getMessage(), npx); } catch (IllegalBlockSizeException ibx) { throw new SecurityException(ibx.getMessage(), ibx); } catch (BadPaddingException bpx) { throw new SecurityException(bpx.getMessage(), bpx); } catch (UnsupportedEncodingException uex) { throw new SecurityException(uex.getMessage(), uex); } catch (InvalidKeySpecException iksx) { throw new SecurityException(iksx.getMessage(), iksx); } catch (InvalidParameterSpecException ipsx) { throw new SecurityException(ipsx.getMessage(), ipsx); } return encPass; }
From source file:com.adeptj.modules.commons.crypto.internal.HashingServiceImpl.java
@Override public byte[] getHashedBytes(char[] plainText, byte[] salt) { Validate.isTrue(ArrayUtils.isNotEmpty(plainText), "plainText array can't be empty!!"); Validate.isTrue(ArrayUtils.isNotEmpty(salt), "salt array can't be empty!!"); try {/* w w w. j a va 2 s . c o m*/ return SecretKeyFactory.getInstance(this.secretKeyAlgo) .generateSecret(new PBEKeySpec(plainText, salt, this.iterationCount, this.keyLength)) .getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { LOGGER.error("Exception while generating hashed bytes!!", ex); throw new CryptoException(ex); } }
From source file:ie.peternagy.jcrypto.algo.AesWrapper.java
/** * Generate secret key from iv, salt, baseKey * *///from w ww . jav a2 s . co m protected final void generateSecretKey() { try { SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec = new PBEKeySpec(new String(baseKey).toCharArray(), salt, 4096, 256); SecretKey generalSecret = factory.generateSecret(keySpec); secretKey = new SecretKeySpec(generalSecret.getEncoded(), ALGORITHM_NAME); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { Logger.getLogger(AesWrapper.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Invalid environment, check max key size", ex); } }
From source file:com.ccstats.crypto.AESWorker.java
/** * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes * as they are necessary for decrypting the encrypted result. * * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely * generated. Finally, the encryption standard is carried out and the encrypted text is obtained. * * @param password the password as a char array. * @param text The plaintext bytes to be encrypted. * * @return The Encrypted text in hexadecimal format. *//*from w w w . j av a 2s .c o m*/ public char[] encrypt(char[] password, byte[] text) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) { this.keyLength = Cipher.getMaxAllowedKeyLength("AES"); System.err.printf( "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n", this.keyLength, this.keyLength); } // hash the password and acquire a securely and randomly generated salt password = hash(new String(password).getBytes(StandardCharsets.UTF_8)); byte[] salt = new byte[20]; new SecureRandom().nextBytes(salt); // acquire the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength); SecretKey key = factory.generateSecret(spec); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); // init the cipher and process the encryption cipher.init(Cipher.ENCRYPT_MODE, keySpec); AlgorithmParameters ap = cipher.getParameters(); byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV(); byte[] result = cipher.doFinal(text); return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt)); }
From source file:grails.plugin.springsecurity.authentication.encoding.PBKDF2PasswordEncoder.java
/** * Computes the PBKDF2 hash of a password. * * @param password the password to hash. * @param salt the salt//from w w w .j av a2 s . c o m * @param iterations the iteration count (slowness factor) * @param bytes the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ protected byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); try { return SecretKeyFactory.getInstance(PBKDF2_ALGORITHM).generateSecret(spec).getEncoded(); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:TDS.Shared.Web.Encryption.java
/** * initializes ciphers and adds jce provider if provided * /*from ww w .j av 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:com.thoughtworks.go.domain.AccessToken.java
static String digestToken(String originalToken, String salt) { try {/*from w w w.jav a2 s . c o m*/ ACCESS_TOKEN_LOGGER.debug( "Generating secret using algorithm: {} with spec: DEFAULT_ITERATIONS: {}, DESIRED_KEY_LENGTH: {}", KEY_ALGORITHM, DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH); SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM); SecretKey key = factory.generateSecret(new PBEKeySpec(originalToken.toCharArray(), salt.getBytes(), DEFAULT_ITERATIONS, DESIRED_KEY_LENGTH)); return Hex.encodeHexString(key.getEncoded()); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } }
From source file:com.titilink.camel.rest.util.PasswordUtils.java
/** * Rabiitsalt?AES????SHA256??.//from w w w. j a va 2 s . c o m * * @param Rabiit ?? * @param salt ? * @return */ public synchronized static Key generateKey(char[] Rabiit, byte[] salt) { SecretKeyFactory factory; SecretKey tmpkey = null; SecretKey secret = null; try { factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); //AES128??AES128 int aeskeylen = AppProperties.getAsInt("AES_KEY_LEN", AES_KEY_LEN); KeySpec keyspec = new PBEKeySpec(Rabiit, salt, ITERATION_COUNT, aeskeylen); tmpkey = factory.generateSecret(keyspec); //AES?? secret = new SecretKeySpec(tmpkey.getEncoded(), ENCODER_AES); } catch (NoSuchAlgorithmException e) { LOGGER.error("generateKey error, no such method exception."); } // "PBKDF2WithHmacSHA256" JDK8?? catch (InvalidKeySpecException e) { LOGGER.error("generateKey error, invalid key exception."); } return secret; }