List of usage examples for javax.crypto SecretKeyFactory getInstance
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.securityfilter.authenticator.persistent.DefaultPersistentLoginManager.java
/** * Set the Encryptin Key used to create a secret key, the secret key is passed * to the Cipher object to be used during encryption and decryption of cookie * values.//from w w w. j ava 2s . com * <p> * <i>NOTE: This entry in the config file must NOT appear before any of the other * encryption config entries</i> * * @param encryptionkey A String containing the encryption key as * defined in config file. This is a required * config entry if protection is set to ALL or ENCRYPTION. */ public void setEncryptionKey(String encryptionkey) { this.encryptionKey = encryptionkey; try { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm); byte[] desKeyData = encryptionkey.getBytes(); DESKeySpec desKeySpec = new DESKeySpec(desKeyData); secretKey = keyFactory.generateSecret(desKeySpec); } catch (Exception e) { System.out.println("Error: " + e); e.printStackTrace(); } }
From source file:org.alfresco.repo.lotus.ws.impl.auth.LtpaAuthenticator.java
private byte[] decrypt(byte[] token, byte[] key, String algorithm) throws Exception { SecretKey sKey = null;// w ww. j av a 2 s .co m if (algorithm.indexOf("AES") != -1) { sKey = new SecretKeySpec(key, 0, 16, "AES"); } else { DESedeKeySpec kSpec = new DESedeKeySpec(key); SecretKeyFactory kFact = SecretKeyFactory.getInstance("DESede"); sKey = kFact.generateSecret(kSpec); } Cipher cipher = Cipher.getInstance(algorithm); if (algorithm.indexOf("ECB") == -1) { if (algorithm.indexOf("AES") != -1) { IvParameterSpec ivs16 = generateIvParameterSpec(key, 16); cipher.init(Cipher.DECRYPT_MODE, sKey, ivs16); } else { IvParameterSpec ivs8 = generateIvParameterSpec(key, 8); cipher.init(Cipher.DECRYPT_MODE, sKey, ivs8); } } else { cipher.init(Cipher.DECRYPT_MODE, sKey); } return cipher.doFinal(token); }
From source file:LicenseGenerator.java
/** * //from w w w .j a v a2 s.co m * * * @param src * ?? * * @param key * 8? * * @return ?? * * @throws Exception * */ public static byte[] decrypt(byte[] src, byte[] key) throws Exception { // DES???? SecureRandom sr = new SecureRandom(); // ?DESKeySpec DESKeySpec dks = new DESKeySpec(key); // ?DESKeySpec?? // SecretKey SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher?? Cipher cipher = Cipher.getInstance("DES"); // Cipher cipher.init(Cipher.DECRYPT_MODE, securekey, sr); // ?? // ?? return cipher.doFinal(src); }
From source file:com.microsoft.aad.adal.CordovaAdalPlugin.java
private SecretKey createSecretKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey tempkey = keyFactory .generateSecret(new PBEKeySpec(key.toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); return secretKey; }
From source file:org.fuin.utils4j.Utils4J.java
/** * Creates a cipher for encryption or decryption. * /*from w ww . j a va 2 s . c o m*/ * @param algorithm * PBE algorithm like "PBEWithMD5AndDES" or * "PBEWithMD5AndTripleDES". * @param mode * Encyrption or decyrption. * @param password * Password. * @param salt * Salt usable with algorithm. * @param count * Iterations. * * @return Ready initialized cipher. * * @throws GeneralSecurityException * Error creating the cipher. */ private static Cipher createCipher(final String algorithm, final int mode, final char[] password, final byte[] salt, final int count) throws GeneralSecurityException { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm); final PBEKeySpec keySpec = new PBEKeySpec(password); final SecretKey key = keyFactory.generateSecret(keySpec); final Cipher cipher = Cipher.getInstance(algorithm); final PBEParameterSpec params = new PBEParameterSpec(salt, count); cipher.init(mode, key, params); return cipher; }
From source file:org.tolven.config.model.CredentialManager.java
private PrivateKey getDERPrivateKey(CertificateKeyDetail keyDetail, char[] password) throws IOException, GeneralSecurityException { File privateKeyFile = new File(keyDetail.getSource()); if (!privateKeyFile.exists()) { throw new RuntimeException("Cannot find PrivateKey file: " + privateKeyFile.getPath()); }/*w w w .j a va 2 s .c om*/ byte[] privateKey = FileUtils.readFileToByteArray(privateKeyFile); EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(privateKey); AlgorithmParameters params = encryptedKeyInfo.getAlgParameters(); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedKeyInfo.getAlgName()); PBEKeySpec passwordSpec = new PBEKeySpec(password); SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec); Cipher cipher = Cipher.getInstance(encryptedKeyInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, secretKey, params); PKCS8EncodedKeySpec keySpec = encryptedKeyInfo.getKeySpec(cipher); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); }
From source file:org.bremersee.common.security.crypto.password.PasswordEncoderImpl.java
/** * <p>// w w w.java 2 s .com * Computes an odd DES key from 56 bits represented as a 7-bytes array. * </p> * <p> * Keeps elements from index {@code offset} to index * {@code offset + 7} of supplied array. * </p> * * @param keyData a byte array containing the 56 bits used to compute the DES * key * @param offset the offset of the first element of the 56-bits key data * @return the odd DES key generated * @throws InvalidKeyException when key is invalid * @throws NoSuchAlgorithmException when algorithm is not available * @throws InvalidKeySpecException when key spec is invalid */ private static Key computeDESKey(final byte[] keyData, final int offset) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { byte[] desKeyData = new byte[8]; int[] k = new int[7]; for (int i = 0; i < 7; i++) k[i] = unsignedByteToInt(keyData[offset + i]); desKeyData[0] = (byte) (k[0] >>> 1); desKeyData[1] = (byte) (((k[0] & 0x01) << 6) | (k[1] >>> 2)); desKeyData[2] = (byte) (((k[1] & 0x03) << 5) | (k[2] >>> 3)); desKeyData[3] = (byte) (((k[2] & 0x07) << 4) | (k[3] >>> 4)); desKeyData[4] = (byte) (((k[3] & 0x0F) << 3) | (k[4] >>> 5)); desKeyData[5] = (byte) (((k[4] & 0x1F) << 2) | (k[5] >>> 6)); desKeyData[6] = (byte) (((k[5] & 0x3F) << 1) | (k[6] >>> 7)); desKeyData[7] = (byte) (k[6] & 0x7F); for (int i = 0; i < 8; i++) desKeyData[i] = (byte) (unsignedByteToInt(desKeyData[i]) << 1); KeySpec desKeySpec = new DESKeySpec(desKeyData); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); return keyFactory.generateSecret(desKeySpec); }
From source file:org.mxupdate.eclipse.properties.ProjectProperties.java
/** * Returns encrypted/decrypted by salt password. Uses SHA-1 Message Digest * Algorithm as defined in NIST's FIPS 180-1. The output of this algorithm * is a 160-bit digest.//from ww w . j av a 2 s . c om * * @param _password password to encrypt / decrypt * @param _decrypt <i>true</i> to decrypt or <i>false</i> to encrypt * @return decrypted / encrypted by salt password * @see #PDE_ALGORITHM * @see #PDE_PASSWORD * @see #PDE_SALT * @see #PDE_ITERATION */ private String decryptEncrypt(final String _password, final boolean _decrypt) { String ret = null; if (_password != null) { try { // create PBE parameter set final PBEParameterSpec pbeParamSpec = new PBEParameterSpec(ProjectProperties.PDE_SALT, ProjectProperties.PDE_ITERATION); final PBEKeySpec pbeKeySpec = new PBEKeySpec(ProjectProperties.PDE_PASSWORD, ProjectProperties.PDE_SALT, ProjectProperties.PDE_ITERATION); final SecretKeyFactory keyFac = SecretKeyFactory.getInstance(ProjectProperties.PDE_ALGORITHM); final SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); final Cipher cipher = Cipher.getInstance(pbeKey.getAlgorithm()); if (_decrypt) { cipher.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec); // decode base64 to get bytes final byte[] dec = Base64.decodeBase64(_password.getBytes(ProjectProperties.ENCODING)); // decrypt final byte[] ciphertext = cipher.doFinal(dec); ret = new String(ciphertext, ProjectProperties.ENCODING); } else { cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); final byte[] pwdText = _password.getBytes(ProjectProperties.ENCODING); // encrypt the cleartext final byte[] ciphertext = cipher.doFinal(pwdText); ret = new String(Base64.encodeBase64(ciphertext), ProjectProperties.ENCODING); } } catch (final Exception e) { throw new Error(e); } } return ret; }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
@Override public boolean changePassphrase(String oldPassphrase, String newPassphrase) { SecretKeyFactory secretKeyFactory; File headerFileOld = new File(this.vaultPath + VAULT_HEADER_FILENAME); File headerFileNew = new File(this.vaultPath + VAULT_HEADER_FILENAME + "NEW"); if (!headerFileNew.exists()) { try {// www . ja va 2 s. com // Decrypt AES encryption key secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM); SecretKey oldKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(oldPassphrase.toCharArray(), vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT)); Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE); c.init(Cipher.UNWRAP_MODE, oldKeyFromPassphrase, new IvParameterSpec(vaultHeader.getVaultIV().toByteArray())); Key decryptedKey = c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(), KEY_ALGORITHM, Cipher.SECRET_KEY); // Create new vault nonce and salt byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE]; byte[] salt = new byte[SALT_SIZE_BYTE]; secureRandom.nextBytes(vaultNonce); secureRandom.nextBytes(salt); int pbkdf2Iterations = generatePBKDF2IterationCount(newPassphrase, salt); // Create new key for AES key encryption SecretKey newKeyFromPassphrase = secretKeyFactory.generateSecret( new PBEKeySpec(newPassphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT)); writeVaultHeader(headerFileNew, vaultNonce, salt, pbkdf2Iterations, decryptedKey, newKeyFromPassphrase); } catch (Exception e) { Util.log("Error while reading or creating new vault header!"); return false; } } else { Util.log("New header file already exists. Cannot change passphrase!"); return false; } // Try to parse new header file try { FileInputStream headerInputStream = new FileInputStream(headerFileNew); vaultHeader = VaultHeader.parseFrom(headerInputStream); } catch (Exception e) { Util.log("Cannot read vault header!"); headerFileNew.delete(); return false; } // Delete old header file and replace with new header file if (!headerFileOld.delete()) { headerFileNew.delete(); Util.log("Cannot delete old vault header!"); return false; } try { org.apache.commons.io.FileUtils.copyFile(headerFileNew, headerFileOld); } catch (IOException e) { Util.log("Cannot replace old vault header!"); return false; } headerFileNew.delete(); return true; }
From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java
/** * @param salt number of the key./*from www . j a v a 2 s. c o m*/ * @return the CupherKey. * @throws UnsupportedEncodingException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ private Key getCiperKey(byte[] salt) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); // hashing the password 65K times takes 151ms, hashing 256 times takes 2ms. // Since the salt has 2^^72 values, 256 times is probably good enough. KeySpec spec = new PBEKeySpec(sharedKey.toCharArray(), salt, 256, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey key = new SecretKeySpec(tmp.getEncoded(), "AES"); return key; }