List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec
public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
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.// ww w . j av a 2 s . co m * * @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:com.streamsets.lib.security.http.PasswordHasher.java
protected String computeHash(String version, int iterations, byte[] salt, String valueTohash) { long start = System.currentTimeMillis(); try {/* ww w.ja v a2 s . c om*/ // yield CPU when this method is run in a tight loop Thread.yield(); PBEKeySpec spec = new PBEKeySpec(valueTohash.toCharArray(), salt, iterations, getKeyLength()); byte[] hash = SECRET_KEY_FACTORIES.get(version).generateSecret(spec).getEncoded(); return version + ":" + iterations + ":" + Hex.encodeHexString(salt) + ":" + Hex.encodeHexString(hash); } catch (Exception ex) { throw new RuntimeException(ex); } finally { LOG.trace("Computing password hash '{}' with '{}' iterations took '{}msec'", version, iterations, System.currentTimeMillis() - start); } }
From source file:eu.eubrazilcc.lvl.storage.security.shiro.CryptProvider.java
/** * Joins the tokens and dates provided as parameters with a salt generated from {@link #DEFAULT_STRENGTH} random bytes and computes a digest using * the PBKDF2 key derivation function./*from ww w. ja va2 s. c om*/ * @param tokens - list of input tokens * @param dates - list of input dates * @return a digest of the input parameters (tokens and dates). * @throws IOException is thrown if the computation of the digest fails. * @see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html">JCA Standard Algorithm Name Documentation</a> */ private static byte[] digest(final @Nullable String[] tokens, @Nullable final Date[] dates) throws IOException { try { String mixName = ""; if (tokens != null) { for (final String token : tokens) { mixName += (token != null ? token.trim() : ""); } } if (dates != null) { for (final Date date : dates) { mixName += (date != null ? Long.toString(date.getTime()) : ""); } } // compute digest final byte[] bytesOfMixName = mixName.getBytes(UTF_8.name()); final char[] charOfMixName = new String(bytesOfMixName).toCharArray(); final byte[] salt = generateSalt(SALT_BYTES_SIZE); final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final PBEKeySpec spec = new PBEKeySpec(charOfMixName, salt, KEY_DEVIATION_ITERATIONS, SALT_BYTES_SIZE * 8); return factory.generateSecret(spec).getEncoded(); } catch (Exception e) { throw new IOException("Digest computation has failed", e); } }
From source file:com.mb.framework.util.SecurityUtil.java
/** * /*ww w.j av a 2 s .c o m*/ * This method is used for decrypt by using Algorithm - AES/CBC/PKCS5Padding * * @param String * @return String * @throws Exception */ @SuppressWarnings("static-access") public static String decryptAESPBKDF2(String encryptedText) throws Exception { byte[] saltBytes = salt.getBytes("UTF-8"); byte[] encryptedTextBytes = new Base64().decodeBase64(encryptedText); // Derive the key SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), saltBytes, pswdIterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // Decrypt the message Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5PADDING_ALGO); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); byte[] decryptedTextBytes = null; try { decryptedTextBytes = cipher.doFinal(encryptedTextBytes); } catch (IllegalBlockSizeException e) { LOGGER.error("error " + e.getMessage()); } catch (BadPaddingException e) { LOGGER.error("error " + e.getMessage()); } return new String(decryptedTextBytes); }
From source file:org.openmrs.module.clinicalsummary.web.controller.upload.UploadSummariesController.java
public void validate(final String filename, final String password) throws Exception { String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED), "."); ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename)); byte[] initVector = null; byte[] encryptedSampleBytes = null; Enumeration<? extends ZipEntry> entries = encryptedFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = entries.nextElement(); String zipEntryName = zipEntry.getName(); if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); initVector = FileCopyUtils.copyToByteArray(inputStream); if (initVector.length != IV_SIZE) { throw new Exception("Secret file is corrupted or invalid secret file are being used."); }/*from w ww . j a v a2 s. c om*/ } else if (zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)) { InputStream inputStream = encryptedFile.getInputStream(zipEntry); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(inputStream, baos); encryptedSampleBytes = baos.toByteArray(); } } if (initVector != null && encryptedSampleBytes != null) { SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY); KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128); SecretKey tmp = factory.generateSecret(spec); // generate the secret key SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); // create the cipher Cipher cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(initVector)); // decrypt the sample ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encryptedSampleBytes); CipherInputStream cipherInputStream = new CipherInputStream(byteArrayInputStream, cipher); ByteArrayOutputStream baos = new ByteArrayOutputStream(); FileCopyUtils.copy(cipherInputStream, baos); String sampleText = baos.toString(); if (!sampleText.contains("This is sample text")) { throw new Exception("Upload parameters incorrect!"); } } }
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 w w .j a v a2s. c o m */ public static byte[] pbkdf128(String... args) { byte[] salt = new byte[128]; Bytes.random(salt); StringBuilder sb = new StringBuilder(); for (String s : args) { sb.append(s); } 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.bcmcgroup.flare.client.ClientUtil.java
/** * Decrypt a string value/*from w ww. j ava 2s . co m*/ * * @param encryptedText the text String to be decrypted * @return the decrypted String * */ public static String decrypt(String encryptedText) { try { byte[] saltBytes = salt.getBytes("UTF-8"); byte[] encryptedTextBytes = Base64.decodeBase64(encryptedText); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize); SecretKey secretKey = factory.generateSecret(spec); SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES"); // Decrypt the message, given derived key and initialization vector. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes)); byte[] decryptedTextBytes = null; try { decryptedTextBytes = cipher.doFinal(encryptedTextBytes); } catch (IllegalBlockSizeException e) { logger.error("IllegalBlockSizeException when attempting to decrypt a string."); } catch (BadPaddingException e) { logger.error("BadPaddingException when attempting to decrypt a string."); } if (decryptedTextBytes != null) { return new String(decryptedTextBytes); } } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException when attempting to decrypt a string. "); } catch (InvalidKeySpecException e) { logger.error("InvalidKeySpecException when attempting to decrypt a string. "); } catch (NoSuchPaddingException e) { logger.error("NoSuchPaddingException when attempting to decrypt a string. "); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException when attempting to decrypt a string. "); } catch (InvalidKeyException e) { logger.error("InvalidKeyException when attempting to decrypt a string. "); } catch (InvalidAlgorithmParameterException e) { logger.error("InvalidAlgorithmParameterException when attempting to decrypt a string. "); } return null; }
From source file:com.beligum.core.utils.Toolkit.java
public static String hash(String password, String salt) { KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 2048, 160); try {/* w ww .j av a 2 s . co m*/ SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] hash = f.generateSecret(spec).getEncoded(); return new String(Hex.encodeHex(hash)); } catch (Exception e) { return null; } }
From source file:org.everit.osgi.password.encryptor.pbkdf2.internal.PBKDF2PasswordEncryptorComponent.java
private String encryptSecure(final byte[] salt, final String plainPassword, final String algorithm) throws NoSuchAlgorithmException, InvalidKeySpecException { int deriverdKeyLenght = PBKDF2PasswordEncryptorConstants.SUPPORTED_ALGORITHMS_AND_KEY_LENGTHS .get(algorithm);/*from ww w . j a v a 2 s . c om*/ KeySpec spec = new PBEKeySpec(plainPassword.toCharArray(), salt, iterationCount, deriverdKeyLenght); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algorithm); byte[] passwordDigest = secretKeyFactory.generateSecret(spec).getEncoded(); byte[] passwordDigestBase64 = Base64.encodeBase64(passwordDigest); String passwordDigestBase64StringUTF8 = StringUtils.newStringUtf8(passwordDigestBase64); byte[] saltBase64 = Base64.encodeBase64(salt); String saltBase64StringUTF8 = StringUtils.newStringUtf8(saltBase64); return SEPARATOR_START + algorithm + SEPARATOR_END + SEPARATOR_START + saltBase64StringUTF8 + SEPARATOR_END + passwordDigestBase64StringUTF8; }
From source file:io.github.goadinggoat.BungeeQuarantine.Commands.AcceptRules.java
private static String hash(String password, byte[] salt) { SecretKeyFactory f;/* w ww .ja v a 2 s .co m*/ SecretKey key; try { f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512"); key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen)); return Base64.encodeBase64String(key.getEncoded()); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeySpecException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }