List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec
public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
From source file:Crypto.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * /*w w w. j a va2 s. c o m*/ * @param initvec * @param salt * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException */ public void setupDecrypt(String initvec, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, DecoderException { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; // since we pass it as a string of input, convert to a actual byte buffer here mSalt = Hex.decodeHex(salt.toCharArray()); Db("got salt " + Hex.encodeHexString(mSalt)); // get initialization vector from passed string mInitVec = Hex.decodeHex(initvec.toCharArray()); Db("got initvector :" + Hex.encodeHexString(mInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Decrypt the message, given derived key and initialization vector. */ mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec)); }
From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java
/** * Creates a key that can be used with a cryptographic service provider. The key is computed from * the specified password and protected with the specified salt. * @param password the password from which the key is computed. * @param salt the salt that is used to protect the key from dictionary attacks. * @return a key that can be used with a cryptographic service provider. * @throws Exception if an error occurs in the execution of the operation. */// www. j a v a2s . co m public static SecretKey generateKey(final String password, final byte[] salt) throws Exception { SecretKey secret; if (UNLIMITED_CRYPTOGRAPHY_AVAILABLE) { // bouncycastle equivalent: SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC") final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); } else { // bouncycastle equivalent: SecretKeyFactory.getInstance("PBEWITHSHA256AND128BITAES-CBC-BC") final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 128); secret = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); } return secret; }
From source file:graphene.util.crypto.PasswordHash.java
/** * Computes the PBKDF2 hash of a password. * /*w w w.j a va2 s .c om*/ * @param password * the password to hash. * @param salt * the salt * @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(final char[] password, final byte[] salt, final int iterations, final int bytes) throws NoSuchAlgorithmException, InvalidKeySpecException { final PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); final SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); }
From source file:org.jumpmind.security.SecurityService.java
protected SecretKey getDefaultSecretKey() throws Exception { String keyPassword = nextSecureHexString(8); KeySpec keySpec = new PBEKeySpec(keyPassword.toCharArray(), SecurityConstants.SALT, SecurityConstants.ITERATION_COUNT, 56); SecretKey secretKey = SecretKeyFactory.getInstance(SecurityConstants.ALGORITHM).generateSecret(keySpec); return secretKey; }
From source file:org.apache.hadoop.hbase.io.crypto.Encryption.java
/** * Return a 128 bit key derived from the concatenation of the supplied * arguments using PBKDF2WithHmacSHA1 at 10,000 iterations. * /*from w ww. j a v a2 s . co m*/ */ public static byte[] pbkdf128(byte[]... args) { byte[] salt = new byte[128]; Bytes.random(salt); StringBuilder sb = new StringBuilder(); for (byte[] b : args) { sb.append(Arrays.toString(b)); } PBEKeySpec spec = new PBEKeySpec(sb.toString().toCharArray(), salt, 10000, 128); try { return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } }
From source file:com.ccstats.crypto.AESWorker.java
/** * Decrypting text that is encrypted by the advanced encryption standard. * * @param password The char array containing of the plaintext password * @param encryptedBlock The Encrypted text to be targeted and decrypted. * * @return The decrypted byte array of the encrypted text. *//*from w w w . j a va 2 s .c om*/ public byte[] decrypt(char[] password, char[] encryptedBlock) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, DecoderException { 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 with the MD5 function and decode the encryptedBlock password = hash(new String(password).getBytes(StandardCharsets.UTF_8)); byte[] decoded = Hex.decodeHex(encryptedBlock); // The decoded byte array has the IV, encryptedText, and salt bytes stored in that order. // The IV bytes are of length 16 and salt is of length 20. byte[] encryptedText = new byte[decoded.length - 36], ivBytes = new byte[16], salt = new byte[20]; // The decoded bytes are ordered in the following form: ivBytes + encryptedText + saltBytes. // Extract the bytes into their corresponding array. System.arraycopy(decoded, 0, ivBytes, 0, ivBytes.length); System.arraycopy(decoded, ivBytes.length, encryptedText, 0, encryptedText.length); System.arraycopy(decoded, decoded.length - salt.length, salt, 0, salt.length); // generate the key from the acquired data 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"); // finally, attempt to decrypt the encryptedText cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes)); return cipher.doFinal(encryptedText); }
From source file:org.apache.ofbiz.base.crypto.HashCrypt.java
public static String pbkdf2HashCrypt(String hashType, String salt, String value) { char[] chars = value.toCharArray(); if (UtilValidate.isEmpty(salt)) { salt = getSalt();/*from w w w .j a va2 s.c o m*/ } try { PBEKeySpec spec = new PBEKeySpec(chars, salt.getBytes(UtilIO.getUtf8()), PBKDF2_ITERATIONS, 64 * 4); SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType); byte[] hash = Base64.encodeBase64(skf.generateSecret(spec).getEncoded()); String pbkdf2Type = null; switch (hashType) { case "PBKDF2WithHmacSHA1": pbkdf2Type = PBKDF2_SHA1; break; case "PBKDF2WithHmacSHA256": pbkdf2Type = PBKDF2_SHA256; break; case "PBKDF2WithHmacSHA384": pbkdf2Type = PBKDF2_SHA384; break; case "PBKDF2WithHmacSHA512": pbkdf2Type = PBKDF2_SHA512; break; default: pbkdf2Type = PBKDF2_SHA1; } StringBuilder sb = new StringBuilder(); sb.append("{").append(pbkdf2Type).append("}"); sb.append(PBKDF2_ITERATIONS).append("$"); sb.append(org.apache.ofbiz.base.util.Base64.base64Encode(salt)).append("$"); sb.append(new String(hash)).toString(); return sb.toString(); } catch (InvalidKeySpecException e) { throw new GeneralRuntimeException("Error while creating SecretKey", e); } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e); } }
From source file:ropes.Crypto.java
/** * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). * We have the password from initializing the class. pass the iv and salt here which is * obtained when encrypting the file initially. * // w w w . j av a 2 s .co m * @param initvec * @param salt * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws DecoderException */ public void setupDecrypt(String initvec, String salt) { try { SecretKeyFactory factory = null; SecretKey tmp = null; SecretKey secret = null; // since we pass it as a string of input, convert to a actual byte buffer here mSalt = Hex.decodeHex(salt.toCharArray()); Db("got salt " + Hex.encodeHexString(mSalt)); // get initialization vector from passed string mInitVec = Hex.decodeHex(initvec.toCharArray()); Db("got initvector :" + Hex.encodeHexString(mInitVec)); /* Derive the key, given password and salt. */ // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security" // The end user must also install them (not compiled in) so beware. // see here: // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS); tmp = factory.generateSecret(spec); secret = new SecretKeySpec(tmp.getEncoded(), "AES"); /* Decrypt the message, given derived key and initialization vector. */ mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec)); } catch (DecoderException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchPaddingException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeyException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.kuzumeji.platform.standard.SecurityService.java
/** * ???/* w w w . java 2 s. c om*/ * <dl> * <dt>? * <dd>PBKDF2??????? * </dl> * @param password * @param salt * @return ?(?) */ public byte[] createCommonKey(final char[] password, final byte[] salt) { try { return SecretKeyFactory.getInstance(PBKDF2_ALGO_NAME) .generateSecret(new PBEKeySpec(password, salt, PBE_ITER_COUNT, PBE_KEY_LENGTH)).getEncoded(); } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } }
From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java
private SecretKey generateKey(String password, byte[] salt) throws CryptographyException { PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, pbeIterationCount, pbeKeyLength); SecretKeyFactory factory;/* w ww .j av a 2 s . c o m*/ SecretKey tmp; try { factory = SecretKeyFactory.getInstance(pbeAlgorithm); tmp = factory.generateSecret(pbeKeySpec); } catch (NoSuchAlgorithmException e) { throw new CryptographyException(e.getMessage()); } catch (InvalidKeySpecException e) { throw new CryptographyException(e.getMessage()); } SecretKey secret = new SecretKeySpec(tmp.getEncoded(), keyGenerator); return secret; }