/** * Computes the PBKDF2 hash of a password. * * @param password the password to hash. * @param salt the salt * @param iterations the iteration count (slowness factor) * @param bytes the length of the hash to compute in bytes * @return the PBDKF2 hash of the password */ private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes) { PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8); SecretKeyFactory skf = null; try { skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM); return skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException ignore) { return null; } catch (InvalidKeySpecException e) { throw new IllegalArgumentException(e); } }
private byte[] decryptPBE(byte[] cipherBytes) { PBECipherProvider pbecp = (PBECipherProvider) cipherProvider; final EncryptionMethod encryptionMethod = EncryptionMethod.forAlgorithm(algorithm); // Extract salt int saltLength = CipherUtility.getSaltLengthForAlgorithm(algorithm); byte[] salt = new byte[saltLength]; System.arraycopy(cipherBytes, 0, salt, 0, saltLength); byte[] actualCipherBytes = Arrays.copyOfRange(cipherBytes, saltLength, cipherBytes.length); // Determine necessary key length int keyLength = CipherUtility.parseKeyLengthFromAlgorithm(algorithm); // Generate cipher try { Cipher cipher = pbecp.getCipher(encryptionMethod, new String(password.getPassword()), salt, keyLength, false); // Write IV if necessary (allows for future use of PBKDF2, Bcrypt, or Scrypt) // byte[] iv = new byte[0]; // if (cipherProvider instanceof RandomIVPBECipherProvider) { // iv = cipher.getIV(); // } // Decrypt the plaintext return cipher.doFinal(actualCipherBytes); } catch (Exception e) { throw new EncryptionException("Could not decrypt sensitive value", e); } }
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_LENGTH); Arrays.fill(password, Character.MIN_VALUE); try { SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); return skf.generateSecret(spec).getEncoded(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new AssertionError("Error while hashing a password: " + e.getMessage(), e); } finally { spec.clearPassword();
} else { boolean nonNullsEqual = a.getIterationCount() == b.getIterationCount() && a.getKeyLength() == b.getKeyLength() && Arrays.equals(a.getSalt(), b.getSalt()); passwordsEqual = CryptoUtils.constantTimeEquals(a.getPassword(), b.getPassword()); } catch (IllegalStateException e) { logger.warn("Encountered an error trying to compare password equality (one or more passwords have been cleared)");
private String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException { SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(habridgeKey)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8"))); }
private static PKCS8EncodedKeySpec createKeySpec(byte[] keyBytes, String password) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { if (Strings.isNullOrEmpty(password)) { return new PKCS8EncodedKeySpec(keyBytes); } final EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(keyBytes); final SecretKeyFactory kf = SecretKeyFactory.getInstance(pkInfo.getAlgName()); final PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); final SecretKey secretKey = kf.generateSecret(keySpec); @SuppressWarnings("InsecureCryptoUsage") final Cipher cipher = Cipher.getInstance(pkInfo.getAlgName()); cipher.init(Cipher.DECRYPT_MODE, secretKey, pkInfo.getAlgParameters()); return pkInfo.getKeySpec(cipher); }
Args.notNull(salt, "salt"); SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algo.algoName()); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKey pbeKey = secretKeyFactory.generateSecret(pbeKeySpec); Cipher cipher = Cipher.getInstance(algo.algoName()); PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, iterationCount); cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParameterSpec); pbeKeySpec.clearPassword(); byte[] iv = cipher.getIV(); int ivLen = (iv == null) ? 0 : iv.length; if (ivLen > 255) {
try { logger.debug("Transforming the password into a secret key..."); SecretKeyFactory passwordFactory = SecretKeyFactory.getInstance(PASSWORD_ENCODING_TYPE); PBEKeySpec passwordSpec = new PBEKeySpec(password); SecretKey passwordKey = passwordFactory.generateSecret(passwordSpec); passwordSpec.clearPassword(); Cipher cipher = Cipher.getInstance(PASSWORD_ENCODING_TYPE); cipher.init(Cipher.ENCRYPT_MODE, passwordKey); keyBytes = key.getEncoded(); byte[] encryptedBytes = cipher.doFinal(keyBytes); AlgorithmParameters params = cipher.getParameters(); EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(params, encryptedBytes) ; try { passwordKey.destroy(); } catch (DestroyFailedException e) {} buffer.append(encodeBytes(encryptedKeyInfo.getEncoded(), indentation)); buffer.append("\n").append(indentation).append("-----END ENCRYPTED PRIVATE KEY-----"); String result = buffer.toString();
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec); byte[] ciphertext = pbeCipher.doFinal(encodedprivkey); EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext); byte[] encryptedPkcs8 = encinfo.getEncoded();
public AesBytesEncryptor(String password, CharSequence salt, BytesKeyGenerator ivGenerator, CipherAlgorithm alg) { PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray(), Hex.decode(salt), 1024, 256); SecretKey secretKey = newSecretKey("PBKDF2WithHmacSHA1", keySpec); this.secretKey = new SecretKeySpec(secretKey.getEncoded(), "AES"); this.alg = alg; this.encryptor = alg.createCipher(); this.decryptor = alg.createCipher(); this.ivGenerator = ivGenerator != null ? ivGenerator : alg.defaultIvGenerator(); }
private static byte[] function(char[] password, byte[] salt) { try { PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, HASH_SIZE * Byte.SIZE); return factory.generateSecret(spec).getEncoded(); } catch (InvalidKeySpecException e) { throw new SecurityException(e); } }
/** * Method to compute masked password based on class attributes. * * @return masked password prefixed with {link @PicketBoxSecurityVault.PASS_MASK_PREFIX}. * @throws Exception */ private String computeMaskedPassword() throws Exception { // Create the PBE secret key SecretKeyFactory factory = SecretKeyFactory.getInstance(VAULT_ENC_ALGORITHM); char[] password = "somearbitrarycrazystringthatdoesnotmatter".toCharArray(); PBEParameterSpec cipherSpec = new PBEParameterSpec(salt.getBytes(CHARSET), iterationCount); PBEKeySpec keySpec = new PBEKeySpec(password); SecretKey cipherKey = factory.generateSecret(keySpec); String maskedPass = PBEUtils.encode64(keystorePassword.getBytes(CHARSET), VAULT_ENC_ALGORITHM, cipherKey, cipherSpec); return PicketBoxSecurityVault.PASS_MASK_PREFIX + maskedPass; }
.replace("-----END ENCRYPTED PRIVATE KEY-----", ""); byte[] encryptedBytes = decodeString(base64Encoded); EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(encryptedBytes) ; SecretKeyFactory passwordFactory = SecretKeyFactory.getInstance(PASSWORD_ENCODING_TYPE); PBEKeySpec passwordSpec = new PBEKeySpec(password); SecretKey passwordKey = passwordFactory.generateSecret(passwordSpec); passwordSpec.clearPassword(); PKCS8EncodedKeySpec pkcs8KeySpec = encryptedKeyInfo.getKeySpec(passwordKey) ; KeyFactory keyFactory = KeyFactory.getInstance(ASYMMETRIC_KEY_TYPE); PrivateKey result = keyFactory.generatePrivate(pkcs8KeySpec); try { passwordKey.destroy(); } catch (DestroyFailedException e) {}
@Override public byte[] hash(char[] chars, byte[] salt) { final PBEKeySpec spec = new PBEKeySpec(chars, salt, 2048, 512); final byte[] encoded = generateSecretKey(spec).getEncoded(); spec.clearPassword(); return encoded; }
public PrivateKey decryptKey(byte[] pkcs8Data, char[] password) throws Exception { PBEKeySpec pbeSpec = new PBEKeySpec(password); EncryptedPrivateKeyInfo pkinfo = new EncryptedPrivateKeyInfo(pkcs8Data); SecretKeyFactory skf = SecretKeyFactory.getInstance(pkinfo.getAlgName()); Key secret = skf.generateSecret(pbeSpec); PKCS8EncodedKeySpec keySpec = pkinfo.getKeySpec(secret); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePrivate(keySpec); }
@Override public Credentials getCredentials(String alias) { try { 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); } }
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8"))); SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD)); Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES"); pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20)); return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
throw new RuntimeException("Error creating SecretKey", e); final SecretKeySpec result = new SecretKeySpec(secretKey.getEncoded(), ALGORITHM); spec.clearPassword(); return result;
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBE"); KeyStore.PasswordProtection password = new KeyStore.PasswordProtection("".toCharArray()); EntryType settingType = settingEntry.getValue(); KeyStore.SecretKeyEntry keystoreEntry = (KeyStore.SecretKeyEntry) keystore.getEntry(setting, password); PBEKeySpec keySpec = (PBEKeySpec) keyFactory.getKeySpec(keystoreEntry.getSecretKey(), PBEKeySpec.class); char[] chars = keySpec.getPassword(); keySpec.clearPassword();
/** * Generates a SecretKey. */ public static SecretKey newSecretKey(String algorithm, String password) { return newSecretKey(algorithm, new PBEKeySpec(password.toCharArray())); }