javax.crypto.spec.PBEKeySpec Java Examples

The following examples show how to use javax.crypto.spec.PBEKeySpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Encryption.java    From jdrivesync with Apache License 2.0 7 votes vote down vote up
public InputStream decrypt(InputStream encryptedStream) {
	try {
		char[] password = options.getEncryptPassword().toCharArray();
		byte[] salt = readSalt(encryptedStream);
		byte[] iv = readIv(encryptedStream);
		KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
		SecretKey secret = new SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).getEncoded(), "AES");
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
		byte[] bytes = toByteArray(encryptedStream);
		byte[] decryptedBytes = cipher.doFinal(bytes);
		return new ByteArrayInputStream(decryptedBytes);
	} catch (Exception e) {
		throw new JDriveSyncException(JDriveSyncException.Reason.Encryption, "Failed to decrypt: " + e.getMessage(), e);
	}
}
 
Example #2
Source File: PasswordUtil.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 根据PBE密码生成一把密钥
 * 
 * @param password
 *            生成密钥时所使用的密码
 * @return Key PBE算法密钥
 * */
private static Key getPBEKey(String password) {
	// 实例化使用的算法
	SecretKeyFactory keyFactory;
	SecretKey secretKey = null;
	try {
		keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		// 设置PBE密钥参数
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		// 生成密钥
		secretKey = keyFactory.generateSecret(keySpec);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return secretKey;
}
 
Example #3
Source File: PBKDF2Core.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpec the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example #4
Source File: TestCipherKeyWrapperTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example #5
Source File: KeyCertLoader.java    From WeCross with Apache License 2.0 6 votes vote down vote up
PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
                InvalidKeySpecException, InvalidKeyException,
                InvalidAlgorithmParameterException {

    if (password == null) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory =
            SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example #6
Source File: PBEKey.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a PBE key from a given PBE key specification.
 *
 * @param key the given PBE key specification
 */
PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
    char[] passwd = keySpec.getPassword();
    if (passwd == null) {
        // Should allow an empty password.
        passwd = new char[0];
    }
    // Accept "\0" to signify "zero-length password with no terminator".
    if (!(passwd.length == 1 && passwd[0] == 0)) {
        for (int i=0; i<passwd.length; i++) {
            if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) {
                throw new InvalidKeySpecException("Password is not ASCII");
            }
        }
    }
    this.key = new byte[passwd.length];
    for (int i=0; i<passwd.length; i++)
        this.key[i] = (byte) (passwd[i] & 0x7f);
    Arrays.fill(passwd, '\0');
    type = keytype;
}
 
Example #7
Source File: PasswordUtil.java    From jeewx with Apache License 2.0 6 votes vote down vote up
/**
 * 根据PBE密码生成一把密钥
 * 
 * @param password
 *            生成密钥时所使用的密码
 * @return Key PBE算法密钥
 * */
private static Key getPBEKey(String password) {
	// 实例化使用的算法
	SecretKeyFactory keyFactory;
	SecretKey secretKey = null;
	try {
		keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		// 设置PBE密钥参数
		PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
		// 生成密钥
		secretKey = keyFactory.generateSecret(keySpec);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return secretKey;
}
 
Example #8
Source File: PBKDF2Core.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpec the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example #9
Source File: PBEKey.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a PBE key from a given PBE key specification.
 *
 * @param key the given PBE key specification
 */
PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
    char[] passwd = keySpec.getPassword();
    if (passwd == null) {
        // Should allow an empty password.
        passwd = new char[0];
    }
    // Accept "\0" to signify "zero-length password with no terminator".
    if (!(passwd.length == 1 && passwd[0] == 0)) {
        for (int i=0; i<passwd.length; i++) {
            if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) {
                throw new InvalidKeySpecException("Password is not ASCII");
            }
        }
    }
    this.key = new byte[passwd.length];
    for (int i=0; i<passwd.length; i++)
        this.key[i] = (byte) (passwd[i] & 0x7f);
    Arrays.fill(passwd, '\0');
    type = keytype;
}
 
Example #10
Source File: AESObfuscator.java    From QtAndroidTools with MIT License 6 votes vote down vote up
/**
 * @param salt an array of random bytes to use for each (un)obfuscation
 * @param applicationId application identifier, e.g. the package name
 * @param deviceId device identifier. Use as many sources as possible to
 *    create this unique identifier.
 */
public AESObfuscator(byte[] salt, String applicationId, String deviceId) {
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
        KeySpec keySpec =
            new PBEKeySpec((applicationId + deviceId).toCharArray(), salt, 1024, 256);
        SecretKey tmp = factory.generateSecret(keySpec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
        mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
        mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
    } catch (GeneralSecurityException e) {
        // This can't happen on a compatible Android device.
        throw new RuntimeException("Invalid environment", e);
    }
}
 
Example #11
Source File: PBKDF2Translate.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The key is generating by SecretKeyFactory and its value just copying in
 * the key field of MySecretKey class. So, this is real key derived using
 * the given algorithm.
 *
 * @param passPhrase some string intended to be a password
 * @param algo PBKDF2 algorithm
 * @param salt slat for PBKDF2
 * @param iterationCount iteration count
 * @param keySize key size in bits
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 */
public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt,
        int iterationCount, int keySize)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    this.algorithm = algo;
    this.salt = salt;
    this.itereationCount = iterationCount;
    this.keySize = keySize;
    this.pass = passPhrase;

    PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(),
            this.salt, iterationCount, this.keySize);

    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(algo);

    SecretKey realKey = keyFactory.generateSecret(spec);

    this.keyLength = realKey.getEncoded().length;

    this.key = new byte[this.keyLength];
    System.arraycopy(realKey.getEncoded(), 0, this.key, 0,
            this.keyLength);
}
 
Example #12
Source File: PBEKey.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a PBE key from a given PBE key specification.
 *
 * @param key the given PBE key specification
 */
PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
    char[] passwd = keySpec.getPassword();
    if (passwd == null) {
        // Should allow an empty password.
        passwd = new char[0];
    }
    // Accept "\0" to signify "zero-length password with no terminator".
    if (!(passwd.length == 1 && passwd[0] == 0)) {
        for (int i=0; i<passwd.length; i++) {
            if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) {
                throw new InvalidKeySpecException("Password is not ASCII");
            }
        }
    }
    this.key = new byte[passwd.length];
    for (int i=0; i<passwd.length; i++)
        this.key[i] = (byte) (passwd[i] & 0x7f);
    java.util.Arrays.fill(passwd, ' ');
    type = keytype;
}
 
Example #13
Source File: PBKDF2Core.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpec the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example #14
Source File: Crypter.java    From remixed-dungeon with GNU General Public License v3.0 6 votes vote down vote up
private Cipher getCipher(int cipherMode) throws Exception {		
	String encryptionAlgorithm = "AES";
	
	byte[] salt = {
		    (byte)0x95, (byte)0xaa, (byte)0x21, (byte)0x8c,
		    (byte)0xa9, (byte)0xc8, (byte)0xfe, (byte)0x99
		};
	
	SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
	KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt, 1, 256);
	SecretKey tmp = factory.generateSecret(spec);
	SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
	
	Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
	cipher.init(cipherMode, secret);
	return cipher;
}
 
Example #15
Source File: PBEKey.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a PBE key from a given PBE key specification.
 *
 * @param key the given PBE key specification
 */
PBEKey(PBEKeySpec keySpec, String keytype) throws InvalidKeySpecException {
    char[] passwd = keySpec.getPassword();
    if (passwd == null) {
        // Should allow an empty password.
        passwd = new char[0];
    }
    // Accept "\0" to signify "zero-length password with no terminator".
    if (!(passwd.length == 1 && passwd[0] == 0)) {
        for (int i=0; i<passwd.length; i++) {
            if ((passwd[i] < '\u0020') || (passwd[i] > '\u007E')) {
                throw new InvalidKeySpecException("Password is not ASCII");
            }
        }
    }
    this.key = new byte[passwd.length];
    for (int i=0; i<passwd.length; i++)
        this.key[i] = (byte) (passwd[i] & 0x7f);
    java.util.Arrays.fill(passwd, ' ');
    type = keytype;
}
 
Example #16
Source File: AesCbcWithIntegrity.java    From android-utils with Apache License 2.0 6 votes vote down vote up
/**
 * A function that generates password-based AES & HMAC keys. It prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @param password The password to derive the keys from.
 * @param salt     the salt
 * @return The AES & HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system, or a suitable RNG is     not
 *                                  available
 */
public static SecretKeys generateKeyFromPassword(String password, byte[] salt)
        throws GeneralSecurityException {
    fixPrng();
    //Get enough random bytes for both the AES key and the HMAC key:
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT,
            AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM);
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

    // Split the random bytes into two parts:
    byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS / 8);
    byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS / 8,
            AES_KEY_LENGTH_BITS / 8 + HMAC_KEY_LENGTH_BITS / 8);

    //Generate the AES key
    SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);

    //Generate the HMAC key
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
 
Example #17
Source File: AbstractInAppService.java    From atomic-plugins-inapps with Mozilla Public License 2.0 6 votes vote down vote up
protected void loadCipheredStock(){
    mStock = new HashMap<String, Integer>();

    try {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        String value = preferences.getString("inappservice_stock", "");
        if (value.length() == 0) {
            return;
        }
        final byte[] bytes = Base64.decode(value,Base64.DEFAULT);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(getUniquePseudoID().toCharArray()));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID).getBytes("utf-8"), 20));
        String json = new String(pbeCipher.doFinal(bytes),"utf-8");
        JSONObject object = new JSONObject(json);
        Iterator<?> keys = object.keys();
        while( keys.hasNext() ){
            String pid = (String)keys.next();
            this.mStock.put(pid, object.optInt(pid));
        }

    } catch( Exception e) {
        e.printStackTrace();
    }
}
 
Example #18
Source File: AesCbcWithIntegrity.java    From java-aes-crypto with MIT License 6 votes vote down vote up
/**
 * A function that generates password-based AES and HMAC keys. It prints out exceptions but
 * doesn't throw them since none should be encountered. If they are
 * encountered, the return value is null.
 *
 * @param password The password to derive the keys from.
 * @return The AES and HMAC keys.
 * @throws GeneralSecurityException if AES is not implemented on this system,
 *                                  or a suitable RNG is not available
 */
public static SecretKeys generateKeyFromPassword(String password, byte[] salt) throws GeneralSecurityException {
    fixPrng();
    //Get enough random bytes for both the AES key and the HMAC key:
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt,
            PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS);
    SecretKeyFactory keyFactory = SecretKeyFactory
            .getInstance(PBE_ALGORITHM);
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();

    // Split the random bytes into two parts:
    byte[] confidentialityKeyBytes = copyOfRange(keyBytes, 0, AES_KEY_LENGTH_BITS /8);
    byte[] integrityKeyBytes = copyOfRange(keyBytes, AES_KEY_LENGTH_BITS /8, AES_KEY_LENGTH_BITS /8 + HMAC_KEY_LENGTH_BITS /8);

    //Generate the AES key
    SecretKey confidentialityKey = new SecretKeySpec(confidentialityKeyBytes, CIPHER);

    //Generate the HMAC key
    SecretKey integrityKey = new SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM);

    return new SecretKeys(confidentialityKey, integrityKey);
}
 
Example #19
Source File: PBKDF2HmacSHA1Factory.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a specification (key material) of the given key
 * in the requested format.
 *
 * @param key the key
 *
 * @param keySpecCl the requested format in which the key material shall be
 * returned
 *
 * @return the underlying key specification (key material) in the
 * requested format
 *
 * @exception InvalidKeySpecException if the requested key
 * specification is inappropriate for the given key, or the
 * given key cannot be processed (e.g., the given key has an
 * unrecognized algorithm or format).
 */
protected KeySpec engineGetKeySpec(SecretKey key, Class<?> keySpecCl)
    throws InvalidKeySpecException {
    if (key instanceof javax.crypto.interfaces.PBEKey) {
        // Check if requested key spec is amongst the valid ones
        if ((keySpecCl != null)
            && PBEKeySpec.class.isAssignableFrom(keySpecCl)) {
            javax.crypto.interfaces.PBEKey pKey =
                (javax.crypto.interfaces.PBEKey) key;
            return new PBEKeySpec
                (pKey.getPassword(), pKey.getSalt(),
                 pKey.getIterationCount(), pKey.getEncoded().length*8);
        } else {
            throw new InvalidKeySpecException("Invalid key spec");
        }
    } else {
        throw new InvalidKeySpecException("Invalid key " +
                                           "format/algorithm");
    }
}
 
Example #20
Source File: PBKDF2Wrapper.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Initiate the Cipher object for PBKDF2 algorithm using given "mode".
 *
 * @param mode Cipher mode: encrypt or decrypt
 * @return Cipher object for PBKDF2 algorithm
 * @throws GeneralSecurityException all security exceptions are thrown.
 */
@Override
protected Cipher initCipher(int mode) throws GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(),
            salt, DEFAULT_ITERATION, PKDF2_DEFAULT_KEY_LEN);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(baseAlgo);
    SecretKey key = keyFactory.generateSecret(pbeKeySpec);

    // get Cipher instance
    Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORMATION, provider);
    cipher.init(mode,
            new SecretKeySpec(key.getEncoded(),KEY_ALGORITHM),
            new IvParameterSpec(iv));
    return cipher;
}
 
Example #21
Source File: PBEIdentityLoginModule.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String encode(String secret)
   throws Exception
{
   // Create the PBE secret key
   cipherSpec = new PBEParameterSpec(salt, iterationCount);
   PBEKeySpec keySpec = new PBEKeySpec(pbepass);
   SecretKeyFactory factory = SecretKeyFactory.getInstance(pbealgo);
   SecretKey cipherKey = factory.generateSecret(keySpec);

   // Decode the secret
   Cipher cipher = Cipher.getInstance(pbealgo);
   cipher.init(Cipher.ENCRYPT_MODE, cipherKey, cipherSpec);
   byte[] encoding = cipher.doFinal(secret.getBytes());
   return Base64Utils.tob64(encoding);
}
 
Example #22
Source File: PBMacDoFinalVsUpdate.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}
 
Example #23
Source File: PBMacBuffer.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}
 
Example #24
Source File: SecretKeyFactoryTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void test_PBKDF2_8BIT(char[] password, byte[] salt, int iterations, int keyLength,
                              byte[] expected) throws Exception {
    if (!StandardNames.IS_RI) {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1And8bit");
        KeySpec ks = new PBEKeySpec(password, salt, iterations, keyLength);
        SecretKey key = factory.generateSecret(ks);
        assertTrue(Arrays.equals(expected, key.getEncoded()));
    }

}
 
Example #25
Source File: DefaultPBEWrapper.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Instantiate Cipher for the PBE algorithm.
 *
 * @param mode Cipher mode: encrypt or decrypt.
 * @return Cipher in accordance to the PBE algorithm
 * @throws java.security.GeneralSecurityException
 */
@Override
protected Cipher initCipher(int mode) throws  GeneralSecurityException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    SecretKey key = SecretKeyFactory.getInstance(baseAlgo)
            .generateSecret(new PBEKeySpec(password.toCharArray()));
    Cipher ci = Cipher.getInstance(transformation, provider);
    ci.init(mode, key, new PBEParameterSpec(salt, DEFAULT_ITERATION));
    return ci;
}
 
Example #26
Source File: PageTokenManager.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String decrypt(String property) {
	SecretKeyFactory keyFactory;
	try {
		keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
		SecretKey key = keyFactory.generateSecret(new PBEKeySpec(this.getPasswordCharArray()));
		Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
		pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(this.getSalt().getBytes(), 20));
		return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
	} catch (GeneralSecurityException | IOException e) {
		logger.error("Error in decrypt", e);
	}
	return null;
}
 
Example #27
Source File: EncryptedMapDecorator.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
private static Key getSecretKey(final String secretKeyAlgorithm, final String secretKey,
        final String salt) throws Exception {

    SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY_ALGORITHM);
    KeySpec spec = new PBEKeySpec(secretKey.toCharArray(), char2byte(salt), 65536, 128);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), secretKeyAlgorithm);

    return secret;
}
 
Example #28
Source File: SecureStore.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
/** Write an entry to the store
 *  @param tag Tag that identifies the entry
 *  @param value Value of the entry
 *  @throws Exception on error
 */
public void set(final String tag, final String value) throws Exception
{
    final SecretKey skey = kf.generateSecret(new PBEKeySpec(value.toCharArray()));
    store.setEntry(tag, new KeyStore.SecretKeyEntry(skey), pp);

    // Write file whenever an entry is changed
    store.store(new FileOutputStream(secure_file), store_pass);
}
 
Example #29
Source File: PBECipherWrapper.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public AES(String algo, String passwd)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeySpecException {
    super(algo, 0);

    ci = Cipher.getInstance(algo);

    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo);
    key = skf.generateSecret(new PBEKeySpec(passwd.toCharArray()));
}
 
Example #30
Source File: PBMacDoFinalVsUpdate.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get SecretKey for the given PBKDF2 algorithm.
 *
 * @param thePBKDF2Algorithm - PBKDF2 algorithm
 * @return SecretKey according to thePBKDF2Algorithm
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
protected SecretKey getSecretKey(String thePBKDF2Algorithm)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    // Prepare salt
    byte[] salt = new byte[64]; // PKCS #5 v2.1 recommendation
    new SecureRandom().nextBytes(salt);

    // Generate secret key
    PBEKeySpec pbeKeySpec = new PBEKeySpec(
            "A #pwd# implied to be hidden!".toCharArray(),
            salt, 1000, 128);
    SecretKeyFactory keyFactory
            = SecretKeyFactory.getInstance(thePBKDF2Algorithm);
    return keyFactory.generateSecret(pbeKeySpec);
}