List of usage examples for javax.crypto SecretKeyFactory getInstance
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
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 ww w. j av a 2 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:com.bcmcgroup.flare.client.ClientUtil.java
/** * Decrypt a string value/*w w w . ja va 2s. c o 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: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 www . j ava 2s .com*/ */ 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:jef.tools.security.EncrypterUtil.java
/** * ??3DESKey/*from ww w . j a v a2 s.co m*/ * * @param password * @return */ public static final SecretKey toDESedeKey(String password) { byte[] bb = password.getBytes(); Assert.isTrue(bb.length > 23, "the secretKey for 3DES must be 24 bytes at least."); try { KeySpec keySpec = new DESedeKeySpec(bb); SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec); return key; } catch (GeneralSecurityException e) { throw new RuntimeException(e.getMessage()); } }
From source file:io.github.goadinggoat.BungeeQuarantine.Commands.AcceptRules.java
private static String hash(String password, byte[] salt) { SecretKeyFactory f;/*w w w. j a va 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; }
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 {//from w w w .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:edu.ku.brc.helpers.Encryption.java
/** * Decrypt the string from its array of bytes * @param input the actual string (in bytes) that is to be decrypted * @param password a password, which is really any string, but must be the same string that was used to encrypt it. * @return a byte array of the decrypted chars * @throws Exception in case something goes wrong *///from w w w .j av a 2 s . c o m public static byte[] decrypt(final byte[] input, final char[] password) throws Exception { /* * The first SALT_LENGTH bytes of the input ciphertext are actually the salt, not the * ciphertext. */ byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(input, 0, salt, 0, SALT_LENGTH); /* * We can now create a key from our salt (extracted just above), password, and iteration * count. Same procedure to create the key as in Encryption(). */ PBEKeySpec keyspec = new PBEKeySpec(password, salt, ITERATION_COUNT); SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM); SecretKey key = skf.generateSecret(keyspec); /* * Once again, create a PBEParameterSpec object and a Cipher object. */ PBEParameterSpec paramspec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key, paramspec); /* * Decrypt the data. The parameters we pass into doFinal() instruct it to skip the first * SALT_LENGTH bytes of input (which are actually the salt), and then to Encryption the next * (length - SALT_LENGTH) bytes, which are the real ciphertext. */ byte[] output = cipher.doFinal(input, SALT_LENGTH, input.length - SALT_LENGTH); /* Clear the password and return the generated plaintext. */ keyspec.clearPassword(); return output; }
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 w w w. j a v a2s .co m*/ 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: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 ww .j a v a 2s .c om*/ * @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. *//*from w w w .j av a 2s . c o 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; }