List of usage examples for javax.crypto SecretKeyFactory getInstance
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.ubipass.middleware.web.action.LicenceMgtAction.java
private String getDate(String userName, String licenceKey) throws Exception { // DES????/*from ww w . ja v a 2 s . c o m*/ SecureRandom sr = new SecureRandom(); byte rawKeyData[] = (userName + "midware").getBytes(); // ?DESKeySpec DESKeySpec dks = new DESKeySpec(rawKeyData); // ?DESKeySpec?? // SecretKey SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyFactory.generateSecret(dks); // Cipher?? Cipher cipher = Cipher.getInstance("DES"); // ?Cipher cipher.init(Cipher.DECRYPT_MODE, key, sr); // ?? licenceKey = new String(cipher.doFinal(Base64.decodeBase64(licenceKey.getBytes()))); String[] tmpStr = licenceKey.split("-"); if (tmpStr.length == 2) return tmpStr[1]; throw new InvalidLicenseException(); }
From source file:com.stimulus.archiva.store.MessageStore.java
public void init() throws MessageStoreException { tempfiles = Config.getFileSystem().getTempFiles(); byte[] salt = Config.getConfig().getSalt(); String passPhrase = getPassPhrase(); if (!isDefaultPassPhraseModified()) logger.warn("archiving is disabled. encryption password is not set."); int iterationCount = 17; String algorithm = Config.getConfig().getPBEAlgorithm(); // "PBEWithMD5AndDES") // Create the key try {//from www. java 2 s . c o m KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); key = SecretKeyFactory.getInstance(algorithm).generateSecret(keySpec); paramSpec = new PBEParameterSpec(salt, iterationCount); } catch (java.security.NoSuchAlgorithmException e) { throw new MessageStoreException( "failed to locate desired encryption algorithm {algorithm='" + algorithm + "'", logger); } catch (Exception e) { throw new MessageStoreException(e.toString(), e, logger); } }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException { secureRandom = new SecureRandom(); this.vaultPath = vaultPath; this.encryptionMode = encryptionMode; File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME); if (!headerFile.exists()) { try {//from w w w.ja v a 2 s .com KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(AES_KEY_SIZE_BIT); Key encryptionKey = keyGenerator.generateKey(); byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase); } catch (Exception e) { Util.log("Cannot create vault header!"); e.printStackTrace(); } } try { FileInputStream headerInputStream = new FileInputStream(headerFile); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); e.printStackTrace(); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); } catch (InvalidKeyException e) { throw new InvalidKeyException("Passphrase is wrong!"); } catch (Exception e) { Util.log("Cannot decrypt AES key"); e.printStackTrace(); } }
From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java
/** * PKCS #8 encode and encrypt a private key. * * @return The encrypted encoding//from w w w . jav a 2s. co m * @param privateKey * The private key * @param pbeType * PBE algorithm to use for encryption * @param password * Encryption password * @throws CryptoException * Problem encountered while getting the encoded private key * @throws IOException * If an I/O error occurred */ public static byte[] getEncrypted(PrivateKey privateKey, Pkcs8PbeType pbeType, Password password) throws CryptoException, IOException { try { byte[] pkcs8 = get(privateKey); // Generate PBE secret key from password SecretKeyFactory keyFact = SecretKeyFactory.getInstance(pbeType.jce()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec); // Generate random salt and iteration count byte[] salt = generateSalt(); int iterationCount = generateIterationCount(); // Store in algorithm parameters PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount); AlgorithmParameters params = AlgorithmParameters.getInstance(pbeType.jce()); params.init(pbeParameterSpec); // Create PBE cipher from key and params Cipher cipher = Cipher.getInstance(pbeType.jce()); cipher.init(Cipher.ENCRYPT_MODE, pbeKey, params); // Encrypt key byte[] encPkcs8 = cipher.doFinal(pkcs8); // Create and return encrypted private key information EncryptedPrivateKeyInfo encPrivateKeyInfo = new EncryptedPrivateKeyInfo(params, encPkcs8); return encPrivateKeyInfo.getEncoded(); } catch (GeneralSecurityException ex) { throw new CryptoException("NoEncryptPkcs8PrivateKey.exception.message", ex); } }
From source file:org.kuali.rice.core.impl.encryption.DemonstrationGradeEncryptionServiceImpl.java
/** * //from ww w . jav a 2s . c om * This method generates keys. This method is implementation specific and should not be present in any general purpose interface * extracted from this class. * * @return * @throws Exception */ public static String generateEncodedKey() throws Exception { KeyGenerator keygen = KeyGenerator.getInstance("DES"); SecretKey desKey = keygen.generateKey(); // Create the cipher Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init((Cipher.WRAP_MODE), desKey); SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES"); DESKeySpec desSpec = (DESKeySpec) desFactory.getKeySpec(desKey, javax.crypto.spec.DESKeySpec.class); byte[] rawDesKey = desSpec.getKey(); return new String(Base64.encodeBase64(rawDesKey)); }
From source file:org.pentaho.platform.engine.security.CipherEncryptionService.java
public void afterPropertiesSet() throws ObjectFactoryException { if ((saltString == null) || (algorithm == null) || (encryptionKey == null)) { throw new ObjectFactoryException( "Required properties not set - need Salt, algorithm and encryption key"); }/* w w w. ja v a2s . com*/ if (saltString.length() != this.saltLength) { // Make sure that the salt length is 8 bytes - the PBEParameterSpec doesn't anything but if (saltString.length() < saltLength) { saltString = (saltString + "!@#$%^&*").substring(0, saltLength); // postfix bytes to pad it out } else if (saltString.length() > saltLength) { saltString = saltString.substring(0, saltLength); // Trim off longer than 8-bytes } } byte[] saltBytes = saltString.getBytes(); paramSpec = new PBEParameterSpec(saltBytes, getIterations()); PBEKeySpec skeySpec = new PBEKeySpec(getEncryptionKey().toCharArray(), saltBytes, getIterations()); try { secretKey = SecretKeyFactory.getInstance(getAlgorithm()).generateSecret(skeySpec); } catch (Exception ex) { ex.printStackTrace(); throw new ObjectFactoryException("Encryption requested not available"); } }
From source file:TripleDES.java
/** Read a TripleDES secret key from the specified file */ public static SecretKey readKey(File f) throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException { // Read the raw bytes from the keyfile DataInputStream in = new DataInputStream(new FileInputStream(f)); byte[] rawkey = new byte[(int) f.length()]; in.readFully(rawkey);// w ww . ja v a 2s .co m in.close(); // Convert the raw bytes to a secret key like this DESedeKeySpec keyspec = new DESedeKeySpec(rawkey); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyfactory.generateSecret(keyspec); return key; }
From source file:org.opennms.features.scv.impl.JCEKSSecureCredentialsVault.java
@Override public Credentials getCredentials(String alias) { try {/*from ww w . j a v a2 s . c om*/ KeyStore.PasswordProtection keyStorePP = new KeyStore.PasswordProtection(m_password); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBE"); KeyStore.SecretKeyEntry ske = (KeyStore.SecretKeyEntry) m_keystore.getEntry(alias, keyStorePP); if (ske == null) { return null; } PBEKeySpec keySpec = (PBEKeySpec) factory.getKeySpec(ske.getSecretKey(), PBEKeySpec.class); return fromBase64EncodedByteArray(new String(keySpec.getPassword()).getBytes()); } catch (KeyStoreException | InvalidKeySpecException | NoSuchAlgorithmException | IOException | ClassNotFoundException | UnrecoverableEntryException e) { throw Throwables.propagate(e); } }
From source file:com.networknt.light.util.HashUtil.java
public static boolean validatePassword(String originalPassword, String storedPassword) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] parts = storedPassword.split(":"); int iterations = Integer.parseInt(parts[0]); byte[] salt = fromHex(parts[1]); byte[] hash = fromHex(parts[2]); PBEKeySpec spec = new PBEKeySpec(originalPassword.toCharArray(), salt, iterations, hash.length * 8); SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); byte[] testHash = skf.generateSecret(spec).getEncoded(); int diff = hash.length ^ testHash.length; for (int i = 0; i < hash.length && i < testHash.length; i++) { diff |= hash[i] ^ testHash[i];//from w w w . j a va 2 s . com } return diff == 0; }
From source file:com.ephesoft.dcma.encryption.core.EncryptorDecryptor.java
/** * This method is used to start the encryption process. * // ww w. j av a2 s. c o m * @param data byte[] * @param salt byte[] * @param isEncryption boolean * @return byte[] * @throws CryptographyException {@link CryptographyException} */ public byte[] startCrypting(byte[] data, byte[] salt, boolean isEncryption) throws CryptographyException { KeySpec keySpec = new PBEKeySpec(EncryptionConstants.KEY.toCharArray(), salt, EncryptionConstants.ITERATION_COUNT); SecretKey key; byte[] finalBytes = null; try { key = SecretKeyFactory.getInstance(EncryptionConstants.ALGORITHM).generateSecret(keySpec); Cipher ecipher = Cipher.getInstance(key.getAlgorithm()); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, EncryptionConstants.ITERATION_COUNT); if (isEncryption) { ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); } else { ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } finalBytes = ecipher.doFinal(data); } catch (InvalidKeySpecException e) { if (isEncryption) { LOGGER.error("Encryption : Key used is invalid", e); throw new CryptographyException("Key used is invalid", e); } else { LOGGER.error("Decryption : Key used is invalid", e); throw new CryptographyException("Key used is invalid", e); } } catch (NoSuchAlgorithmException e) { if (isEncryption) { LOGGER.error("Encryption : Algorithm used does not exist", e); throw new CryptographyException("Algorithm used does not exist", e); } else { LOGGER.error("Decryption : Algorithm used does not exist", e); throw new CryptographyException("Algorithm used does not exist", e); } } catch (NoSuchPaddingException e) { if (isEncryption) { LOGGER.error("Encryption : Padding used does not exist", e); throw new CryptographyException("Padding used does not exist", e); } else { LOGGER.error("Decryption : Padding used does not exist", e); throw new CryptographyException("Padding used does not exist", e); } } catch (InvalidKeyException e) { if (isEncryption) { LOGGER.error("Encryption : Key generated is invalid", e); throw new CryptographyException("Key generated is invalid", e); } else { LOGGER.error("Decryption : Key generated is invalid", e); throw new CryptographyException("Key generated is invalid", e); } } catch (InvalidAlgorithmParameterException e) { if (isEncryption) { LOGGER.error("Encryption : Algorithm parameter is invalid", e); throw new CryptographyException("Algorithm parameter is invalid", e); } else { LOGGER.error("Decryption : Algorithm parameter is invalid", e); throw new CryptographyException("Algorithm parameter is invalid", e); } } catch (IllegalBlockSizeException e) { if (isEncryption) { LOGGER.error("Encryption : Block size is illegal", e); throw new CryptographyException("Block size is illegal", e); } else { LOGGER.error("Decryption : Block size is illegal", e); throw new CryptographyException("Block size is illegal", e); } } catch (BadPaddingException e) { if (isEncryption) { LOGGER.error("Encryption : Padding done is invalid", e); throw new CryptographyException("Padding done is invalid", e); } else { LOGGER.error("Decryption : Padding done is invalid", e); throw new CryptographyException("Padding done is invalid", e); } } return finalBytes; }