List of usage examples for javax.crypto SecretKeyFactory getInstance
public static final SecretKeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:ai.serotonin.backup.Base.java
SecretKey createSecretKey(final byte[] salt) throws Exception { final String password = getArchivePassword(); final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); final SecretKey tmp = factory.generateSecret(spec); final SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); return secret; }
From source file:org.apache.ofbiz.base.crypto.HashCrypt.java
public static boolean doComparePbkdf2(String crypted, String password) { try {/* w w w . ja v a 2 s . c o m*/ int typeEnd = crypted.indexOf("}"); String hashType = crypted.substring(1, typeEnd); String[] parts = crypted.split("\\$"); int iterations = Integer.parseInt(parts[0].substring(typeEnd + 1)); byte[] salt = org.apache.ofbiz.base.util.Base64.base64Decode(parts[1]).getBytes(); byte[] hash = Base64.decodeBase64(parts[2].getBytes()); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8); switch (hashType.substring(hashType.indexOf("-") + 1)) { case "SHA256": hashType = "PBKDF2WithHmacSHA256"; break; case "SHA384": hashType = "PBKDF2WithHmacSHA384"; break; case "SHA512": hashType = "PBKDF2WithHmacSHA512"; break; default: hashType = "PBKDF2WithHmacSHA1"; } SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType); 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]; } return diff == 0; } catch (NoSuchAlgorithmException e) { throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e); } catch (InvalidKeySpecException e) { throw new GeneralRuntimeException("Error while creating SecretKey", e); } }
From source file:cz.muni.fi.airportservicelayer.services.StewardServiceImpl.java
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) { try {/*www. j a v a 2s .co m*/ PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:netinf.common.security.impl.CryptoAlgorithmImpl.java
@Override public SecretKey getSecretKeyFromString(String contentAlgorithmName, String password) throws NetInfCheckedSecurityException { try {//w w w. j a va2 s . c o m DESedeKeySpec desKeySpec = new DESedeKeySpec(password.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(contentAlgorithmName); return keyFactory.generateSecret(desKeySpec); } catch (Exception e) { throw new NetInfCheckedSecurityException("Unable to create SecretKey. " + e.getMessage()); } }
From source file:org.chililog.server.common.CryptoUtils.java
/** * <p>/*w ww . j a v a 2 s . c o m*/ * Encrypt a plain text string using AES. The output is an encrypted plain text string. See * http://stackoverflow.com/questions/992019/java-256bit-aes-encryption/992413#992413 * </p> * <p> * The algorithm used is <code>base64(aes(plainText))</code> * </p> * * * @param plainText * text to encrypt * @param password * password to use for encryption * @return encrypted text * @throws ChiliLogException */ public static String encryptAES(String plainText, String password) throws ChiliLogException { try { SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); KeySpec spec = new PBEKeySpec(password.toCharArray(), AES_ENCRYPTION_STRING_SALT, 1024, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); byte[] plainTextBytes = plainText.getBytes("UTF-8"); AlgorithmParameterSpec paramSpec = new IvParameterSpec(AES_ENCRYPTION_INTIALIZATION_VECTOR); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret, paramSpec); byte[] cipherText = cipher.doFinal(plainTextBytes); // Convert hash to string Base64 encoder = new Base64(1000, new byte[] {}, false); return encoder.encodeToString(cipherText); } catch (Exception ex) { throw new ChiliLogException(ex, "Error attempting to encrypt. " + ex.getMessage()); } }
From source file:uk.ac.ox.webauth.crypto.Des3CbcSha1Kd.java
/** * From RFC 3961://w w w. ja v a 2s .c o m * DR(Key, Constant) = k-truncate(E(Key, Constant, initial-cipher-state)) * * Here DR is the random-octet generation function described below, and * DK is the key-derivation function produced from it. In this * construction, E(Key, Plaintext, CipherState) is a cipher, Constant is * a well-known constant determined by the specific usage of this * function, and k-truncate truncates its argument by taking the first k * bits. Here, k is the key generation seed length needed for the * encryption system. * * The output of the DR function is a string of bits; the actual key is * produced by applying the cryptosystem's random-to-key operation on * this bitstring. * * If the Constant is smaller than the cipher block size of E, then it * must be expanded with n-fold() so it can be encrypted. If the output * of E is shorter than k bits, it is fed back into the encryption as * many times as necessary. The construct is as follows (where | * indicates concatentation): * * K1 = E(Key, n-fold(Constant), initial-cipher-state) * K2 = E(Key, K1, initial-cipher-state) * K3 = E(Key, K2, initial-cipher-state) * K4 = ... * * DR(Key, Constant) = k-truncate(K1 | K2 | K3 | K4 ...) */ private static byte[] dr(byte[] key, byte[] constant) throws GeneralSecurityException { // first make a DES3 key SecretKeyFactory factory = SecretKeyFactory.getInstance("DESede"); KeySpec spec = new DESedeKeySpec(key); SecretKey secretKey = factory.generateSecret(spec); // initialise the cipher to use Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding"); cipher.init(ENCRYPT_MODE, secretKey, IV); // ensure the constant is not smaller than the blocksize if (constant.length < cipher.getBlockSize()) { constant = nFold(constant, cipher.getBlockSize() * 8); } // now encrypt until we have at least 21 bytes, the length of a DES3 key byte[] input = constant; byte[] kn = new byte[0]; do { byte[] newKn = cipher.doFinal(input); byte[] oldKn = kn; kn = new byte[oldKn.length + newKn.length]; System.arraycopy(oldKn, 0, kn, 0, oldKn.length); System.arraycopy(newKn, 0, kn, oldKn.length, newKn.length); input = newKn; } while (kn.length < 21); // make sure we are returning exactly 21 bytes if (kn.length != 21) { byte[] newKn = new byte[21]; System.arraycopy(kn, 0, newKn, 0, 21); kn = newKn; } return kn; }
From source file:uk.ac.cam.cl.dtg.segue.auth.SegueLocalAuthenticator.java
/** * Compute the hash of a string using the preconfigured hashing function. * * @param str/*from ww w . ja va 2 s . c om*/ * - string to hash * @param salt * - random string to use as a salt. * @param keyLength * - the key length * @return a byte array of the hash * @throws NoSuchAlgorithmException * - if the configured algorithm is not valid. * @throws InvalidKeySpecException * - if the preconfigured key spec is invalid. */ private byte[] computeHash(final String str, final String salt, final int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException { char[] strChars = str.toCharArray(); byte[] saltBytes = salt.getBytes(); PBEKeySpec spec = new PBEKeySpec(strChars, saltBytes, ITERATIONS, keyLength); SecretKeyFactory key = SecretKeyFactory.getInstance(CRYPTO_ALOGRITHM); return key.generateSecret(spec).getEncoded(); }
From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java
/** * Generates an AES key from the password using PBKDF2. * * @param salt the salt// w ww. j a v a 2s . c o m */ protected Key generateSecretKey(byte[] salt) throws GeneralSecurityException { char[] password = getPassword(); SecretKeyFactory factory = SecretKeyFactory.getInstance(PBKDF2_WITH_HMAC_SHA1); PBEKeySpec spec = new PBEKeySpec(password, salt, PBKDF2_ITERATIONS, PBKDF2_KEY_LENGTH); clearPassword(password); Key derived = factory.generateSecret(spec); spec.clearPassword(); return new SecretKeySpec(derived.getEncoded(), AES); }
From source file:org.apache.xml.security.test.encryption.XMLCipherTester.java
/** * Test encryption using a generated AES 192 bit key that is * encrypted using a 3DES key. Then reverse by decrypting * EncryptedKey by hand//w w w .j av a 2 s. c o m */ public void testAES192ElementAES256KWCipher() throws Exception { Document d = document(); // source Document ed = null; Document dd = null; Element e = (Element) d.getElementsByTagName(element()).item(index()); Element ee = null; String source = null; String target = null; if (haveISOPadding && haveKeyWraps) { source = toString(d); // Set up a Key Encryption Key byte[] bits192 = "abcdefghijklmnopqrstuvwx".getBytes(); DESedeKeySpec keySpec = new DESedeKeySpec(bits192); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); Key kek = keyFactory.generateSecret(keySpec); // Generate a traffic key KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(192); Key key = keygen.generateKey(); cipher = XMLCipher.getInstance(XMLCipher.TRIPLEDES_KeyWrap); cipher.init(XMLCipher.WRAP_MODE, kek); EncryptedKey encryptedKey = cipher.encryptKey(d, key); // encrypt cipher = XMLCipher.getInstance(XMLCipher.AES_192); cipher.init(XMLCipher.ENCRYPT_MODE, key); EncryptedData builder = cipher.getEncryptedData(); KeyInfo builderKeyInfo = builder.getKeyInfo(); if (builderKeyInfo == null) { builderKeyInfo = new KeyInfo(d); builder.setKeyInfo(builderKeyInfo); } builderKeyInfo.add(encryptedKey); ed = cipher.doFinal(d, e); //decrypt key = null; ee = (Element) ed.getElementsByTagName("xenc:EncryptedData").item(0); cipher = XMLCipher.getInstance(); cipher.init(XMLCipher.DECRYPT_MODE, null); EncryptedData encryptedData = cipher.loadEncryptedData(ed, ee); if (encryptedData == null) { System.out.println("ed is null"); } else if (encryptedData.getKeyInfo() == null) { System.out.println("ki is null"); } EncryptedKey ek = encryptedData.getKeyInfo().itemEncryptedKey(0); if (ek != null) { XMLCipher keyCipher = XMLCipher.getInstance(); keyCipher.init(XMLCipher.UNWRAP_MODE, kek); key = keyCipher.decryptKey(ek, encryptedData.getEncryptionMethod().getAlgorithm()); } // Create a new cipher just to be paranoid XMLCipher cipher3 = XMLCipher.getInstance(); cipher3.init(XMLCipher.DECRYPT_MODE, key); dd = cipher3.doFinal(ed, ee); target = toString(dd); Assert.assertEquals(source, target); } else { log.warn("Test testAES192ElementAES256KWCipher skipped as necessary algorithms not available"); } }
From source file:com.microsoft.aad.adal.example.userappwithbroker.MainActivity.java
/** * To call broker, you have to ensure the following: * 1) You have to call {@link AuthenticationSettings#INSTANCE#setUseBroker(boolean)} * and the supplied value has to be true * 2) You have to have to correct set of permissions. * If target API version is lower than 23: * i) You have to have GET_ACCOUNTS, USE_CREDENTIAL, MANAGE_ACCOUNTS declared * in manifest./* w w w . j a v a2 s .c o m*/ * If target API version is 23: * i) USE_CREDENTIAL and MANAGE_ACCOUNTS is already deprecated. * ii) GET_ACCOUNTS permission is now at protection level "dangerous" calling app * is responsible for requesting it. * 3) If you're talking to the broker app without PRT support, you have to have an * WPJ account existed in broker(enroll with intune, or register with Azure * Authentication app). * 4) The two broker apps(Company Portal or Azure Authenticator) cannot go through * broker auth. */ private void setUpADALForCallingBroker() { // Set the calling app will talk to broker // Note: Starting from version 1.1.14, calling app has to explicitly call // AuthenticationSettings.Instance.setUserBroker(true) to call broker. // AuthenticationSettings.Instance.setSkipBroker(boolean) is already deprecated. AuthenticationSettings.INSTANCE.setUseBroker(true); // Provide secret key for token encryption. try { // For API version lower than 18, you have to provide the secret key. The secret key // needs to be 256 bits. You can use the following way to generate the secret key. And // use AuthenticationSettings.Instance.setSecretKey(secretKeyBytes) to supply us the key. // For API version 18 and above, we use android keystore to generate keypair, and persist // the keypair in AndroidKeyStore. Current investigation shows 1)Keystore may be locked with // a lock screen, if calling app has a lot of background activity, keystore cannot be // accessed when locked, we'll be unable to decrypt the cache items 2) AndroidKeystore could // be reset when gesture to unlock the device is changed. // We do recommend the calling app the supply us the key with the above two limitations. if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { // use same key for tests SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC"); SecretKey tempkey = keyFactory.generateSecret( new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), 100, 256)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } } catch (NoSuchAlgorithmException | InvalidKeySpecException | UnsupportedEncodingException ex) { showMessage("Fail to generate secret key:" + ex.getMessage()); } ApplicationInfo appInfo = getApplicationContext().getApplicationInfo(); Log.v(TAG, "App info:" + appInfo.uid + " package:" + appInfo.packageName); // If you're directly talking to ADFS server, you should set validateAuthority=false. SampleTelemetry telemetryDispatcher = new SampleTelemetry(); Telemetry.getInstance().registerDispatcher(telemetryDispatcher, true); }