List of usage examples for javax.crypto SecretKeyFactory generateSecret
public final SecretKey generateSecret(KeySpec keySpec) throws InvalidKeySpecException
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 av a 2s . c o m } 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:spacetraffic.kiv.zcu.cz.gameelement.MinigamePasswordHasher.java
/** * Method for generating key.//www .j a v a 2s .c o m * @return key * @throws Exception */ private Key generateKey() throws Exception { SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM); char[] pdkbf2Password = PDKBF2_PASSWORD.toCharArray(); byte[] salt = SALT.getBytes(CHARSET); KeySpec keySpec = new PBEKeySpec(pdkbf2Password, salt, 65536, 128); SecretKey secretKey = factory.generateSecret(keySpec); byte[] encodedKey = secretKey.getEncoded(); return new SecretKeySpec(encodedKey, "AES"); }
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 ww .j a v a 2s . c om*/ 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:com.sangupta.passcode.PassCode.java
/** * Hash the given password./*from www.j av a 2s.com*/ * * @param password * the master password or passphrase * * @param salt * the salt to be used * * @param entropy * the entropy to be used * * @return the byte-array representing the hash */ private byte[] hash(String password, String salt, int entropy) { // generate the hash try { PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), this.config.iterations, entropy + 12); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); return skf.generateSecret(spec).getEncoded(); } catch (GeneralSecurityException e) { System.out.println("Something went wrong!"); System.exit(0); } return null; }
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; SecretKey tmp;/* w ww . j ava 2s .c om*/ 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; }
From source file:ie.peternagy.jcrypto.algo.AesWrapper.java
/** * Generate secret key from iv, salt, baseKey * *///from w w w . j a v a 2 s . c o 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
/** * 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 ww w. j a v a 2 s . co m*/ 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.kuali.rice.krad.devtools.maintainablexml.EncryptionService.java
private SecretKey unwrapEncodedKeyOld(String key) throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey(); // Create the cipher Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init((Cipher.UNWRAP_MODE), desKey); byte[] bytes = Base64.decodeBase64(key.getBytes()); // If decoding was done with commons-codec 1.3 and the key not ended with '=' bytes[6] = 1;//w ww . j a v a2 s.c o m bytes[7] = 1; SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec keyspec = new DESKeySpec(bytes); SecretKey k = desFactory.generateSecret(keyspec); return k; }
From source file:org.kchine.rpf.db.DBLayer.java
static SecretKey getSecretKey() { try {// w w w .j a v a 2s .c o m DESedeKeySpec keyspec = new DESedeKeySpec(PoolUtils.hexToBytes(_pwdKey)); SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede"); SecretKey k = desEdeFactory.generateSecret(keyspec); return k; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java
/** * Method to initialize the cipher object with the correct encryption algorithm. * * @throws Exception//from w w w . j a v a2 s. com */ protected final 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); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); if (log.isDebugEnabled()) log.debug("Encrypting with: " + secret.getAlgorithm()); cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.ENCRYPT_MODE, secret); }