org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator Java Examples

The following examples show how to use org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator. 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: Mnemonic.java    From hedera-sdk-java with Apache License 2.0 6 votes vote down vote up
@Internal
public byte[] toSeed(String passphrase) {
    final String salt = "mnemonic" + passphrase;

    // BIP-39 seed generation
    final PKCS5S2ParametersGenerator pbkdf2 = new PKCS5S2ParametersGenerator(new SHA512Digest());
    pbkdf2.init(
        toString().getBytes(StandardCharsets.UTF_8),
        salt.getBytes(StandardCharsets.UTF_8),
        2048);

    final KeyParameter key = (KeyParameter) pbkdf2.generateDerivedParameters(512);
    return key.getKey();
}
 
Example #2
Source File: PBKDF2UserAuthenticator.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public String encode(String password, byte[] salt, int rounds)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException {
    PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator();
    generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(
                    password.toCharArray()),
            salt,
            rounds);
    return format("%s:%s:%d", encode(salt),
            encode(((KeyParameter)generator.generateDerivedParameters(s_keylen)).getKey()), rounds);
}
 
Example #3
Source File: PBKDF2CipherProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, byte[] iv, int keyLength, boolean encryptMode) throws Exception {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (!encryptionMethod.isCompatibleWithStrongKDFs()) {
        throw new IllegalArgumentException(encryptionMethod.name() + " is not compatible with PBKDF2");
    }

    String algorithm = encryptionMethod.getAlgorithm();

    final String cipherName = CipherUtility.parseCipherFromAlgorithm(algorithm);
    if (!CipherUtility.isValidKeyLength(keyLength, cipherName)) {
        throw new IllegalArgumentException(String.valueOf(keyLength) + " is not a valid key length for " + cipherName);
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    if (salt == null || salt.length < DEFAULT_SALT_LENGTH) {
        throw new IllegalArgumentException("The salt must be at least " + DEFAULT_SALT_LENGTH + " bytes. To generate a salt, use PBKDF2CipherProvider#generateSalt()");
    }

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(this.prf);
    gen.init(password.getBytes(StandardCharsets.UTF_8), salt, getIterationCount());
    byte[] dk = ((KeyParameter) gen.generateDerivedParameters(keyLength)).getKey();
    SecretKey tempKey = new SecretKeySpec(dk, algorithm);

    KeyedCipherProvider keyedCipherProvider = new AESKeyedCipherProvider();
    return keyedCipherProvider.getCipher(encryptionMethod, tempKey, iv, encryptMode);
}
 
Example #4
Source File: Wallet.java    From web3j with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #5
Source File: MnemonicUtils.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a mnemonic
 * sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" + passphrase (again
 * in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512 is used
 * as the pseudo-random function. The length of the derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing only
 *     valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2 function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    if (isMnemonicEmpty(mnemonic)) {
        throw new IllegalArgumentException("Mnemonic is required to generate a seed");
    }
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}
 
Example #6
Source File: MnemonicUtils.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a mnemonic
 * sentence (in UTF-8 NFKD) used as the password and the string "mnemonic" + passphrase (again
 * in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512 is used
 * as the pseudo-random function. The length of the derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing only
 *     valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2 function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    if (isMnemonicEmpty(mnemonic)) {
        throw new IllegalArgumentException("Mnemonic is required to generate a seed");
    }
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}
 
Example #7
Source File: Wallet.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #8
Source File: Wallet.java    From blockchain with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #9
Source File: AESDecrypterBC.java    From fingen with Apache License 2.0 5 votes vote down vote up
public void init( String pwStr, int keySize, byte[] salt, byte[] pwVerification ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	
	super.saltBytes = salt;

	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	generator.init( pwBytes, salt, ITERATION_COUNT );

	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, this.pwVerificationBytes, 0, 2 );

	if( !ByteArrayHelper.isEqual( this.pwVerificationBytes, pwVerification ) ) {
		throw new ZipException("wrong password - " + ByteArrayHelper.toString(this.pwVerificationBytes) + "/ " + ByteArrayHelper.toString(pwVerification));
	}

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, salt, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
}
 
Example #10
Source File: PBKDF2CipherProvider.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
protected Cipher getInitializedCipher(EncryptionMethod encryptionMethod, String password, byte[] salt, byte[] iv, int keyLength, boolean encryptMode) throws Exception {
    if (encryptionMethod == null) {
        throw new IllegalArgumentException("The encryption method must be specified");
    }

    if (!encryptionMethod.isCompatibleWithStrongKDFs()) {
        throw new IllegalArgumentException(encryptionMethod.name() + " is not compatible with PBKDF2");
    }

    String algorithm = encryptionMethod.getAlgorithm();

    final String cipherName = CipherUtility.parseCipherFromAlgorithm(algorithm);
    if (!CipherUtility.isValidKeyLength(keyLength, cipherName)) {
        throw new IllegalArgumentException(String.valueOf(keyLength) + " is not a valid key length for " + cipherName);
    }

    if (StringUtils.isEmpty(password)) {
        throw new IllegalArgumentException("Encryption with an empty password is not supported");
    }

    if (salt == null || salt.length < DEFAULT_SALT_LENGTH) {
        throw new IllegalArgumentException("The salt must be at least " + DEFAULT_SALT_LENGTH + " bytes. To generate a salt, use PBKDF2CipherProvider#generateSalt()");
    }

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(this.prf);
    gen.init(password.getBytes(StandardCharsets.UTF_8), salt, getIterationCount());
    byte[] dk = ((KeyParameter) gen.generateDerivedParameters(keyLength)).getKey();
    SecretKey tempKey = new SecretKeySpec(dk, algorithm);

    KeyedCipherProvider keyedCipherProvider = new AESKeyedCipherProvider();
    return keyedCipherProvider.getCipher(encryptionMethod, tempKey, iv, encryptMode);
}
 
Example #11
Source File: Wallet.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #12
Source File: Wallet.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
private static byte[] generateAes128CtrDerivedKey(
        byte[] password, byte[] salt, int c, String prf) throws CipherException {

    if (!prf.equals("hmac-sha256")) {
        throw new CipherException("Unsupported prf:" + prf);
    }

    // Java 8 supports this, but you have to convert the password to a character array, see
    // http://stackoverflow.com/a/27928435/3211687

    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(password, salt, c);
    return ((KeyParameter) gen.generateDerivedParameters(256)).getKey();
}
 
Example #13
Source File: AESEncrypterBC.java    From fingen with Apache License 2.0 4 votes vote down vote up
/**
 * Setup AES encryption based on pwBytes using WinZipAES approach
 * with SALT and pwVerification bytes based on password+salt.
 */
public void init( String pwStr, int keySize ) throws ZipException {
	byte[] pwBytes = pwStr.getBytes();
	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	this.saltBytes = createSalt();
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );

	// create 2 byte[16] for two keys and one byte[2] for pwVerification
	// 1. encryption / 2. athentication (via HMAC/hash) /
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT*2 + 16);
	byte[] keyBytes = ((KeyParameter)cipherParameters).getKey();

	this.cryptoKeyBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, 0, cryptoKeyBytes, 0, KEY_SIZE_BYTE );

	this.authenticationCodeBytes = new byte[ KEY_SIZE_BYTE ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE, authenticationCodeBytes, 0, KEY_SIZE_BYTE );

	// based on SALT + PASSWORD (password is probably correct)
	this.pwVerificationBytes = new byte[ 2 ];
	System.arraycopy( keyBytes, KEY_SIZE_BYTE*2, pwVerificationBytes, 0, 2 );

	// create the first 16 bytes of the key sequence again (using pw+salt)
	generator.init( pwBytes, saltBytes, ITERATION_COUNT );
	cipherParameters = generator.generateDerivedParameters(KEY_SIZE_BIT);

	// checksum added to the end of the encrypted data, update on each encryption call
	this.mac = new HMac( new SHA1Digest() );
	mac.init( new KeyParameter(authenticationCodeBytes) );

	this.aesCipher = new SICBlockCipher(new AESEngine());
	this.blockSize = aesCipher.getBlockSize();

	// incremented on each 16 byte block and used as encryption NONCE (ivBytes)
	nonce = 1;
	
	if( LOG.isLoggable(Level.FINEST) ) {
		LOG.finest( "pwBytes   = " + ByteArrayHelper.toString(pwBytes) + " - " + pwBytes.length );
		LOG.finest( "salt      = " + ByteArrayHelper.toString(saltBytes) + " - " + saltBytes.length );
		LOG.finest( "pwVerif   = " + ByteArrayHelper.toString(pwVerificationBytes) + " - " + pwVerificationBytes.length );
	}
}
 
Example #14
Source File: SHA256Implementation.java    From openmeetings with Apache License 2.0 4 votes vote down vote up
private static String hash(String str, byte[] salt, int iter) {
	PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
	gen.init(str.getBytes(StandardCharsets.UTF_8), salt, iter);
	byte[] dk = ((KeyParameter) gen.generateDerivedParameters(KEY_LENGTH)).getKey();
	return Base64.encodeBase64String(dk);
}
 
Example #15
Source File: PBKDF2.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public static byte[] generate(Digest digest, byte[] password, byte[] salt, int iterations, int lengthBits) {
    PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(digest);
    generator.init(password, salt, iterations);
    return ((KeyParameter) generator.generateDerivedParameters(lengthBits)).getKey();
}
 
Example #16
Source File: StreamCryptorPBKDF2.java    From InflatableDonkey with MIT License 4 votes vote down vote up
@Override
public byte[] apply(byte[] password, byte[] salt) {
    PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(digests.get());
    generator.init(password, salt, iterations);
    return ((KeyParameter) generator.generateDerivedParameters(keyLength * 8)).getKey();
}
 
Example #17
Source File: PBKDF2.java    From LiquidDonkey with MIT License 4 votes vote down vote up
PBKDF2() {
    this.generator = new PKCS5S2ParametersGenerator();
}
 
Example #18
Source File: CryptoUtils.java    From hedera-sdk-java with Apache License 2.0 4 votes vote down vote up
static KeyParameter deriveKeySha256(String passphrase, byte[] salt, int iterations, int dkLenBytes) {
    final PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());
    gen.init(passphrase.getBytes(StandardCharsets.UTF_8), salt, iterations);

    return (KeyParameter) gen.generateDerivedParameters(dkLenBytes * 8);
}
 
Example #19
Source File: CryptographicUtilities.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public static byte[] stretchPassword(char[] password, int keyLength, byte[] salt) {
	PBEParametersGenerator generator = new PKCS5S2ParametersGenerator();
	generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(password), salt, 1000);
	KeyParameter params = (KeyParameter)generator.generateDerivedParameters(keyLength);
	return params.getKey();
}
 
Example #20
Source File: MnemonicUtils.java    From blockchain with Apache License 2.0 3 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a
 * mnemonic sentence (in UTF-8 NFKD) used as the password and the string "mnemonic"
 * + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set
 * to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the
 * derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing
 *                 only valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2
 *                   function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    validateMnemonic(mnemonic);
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}
 
Example #21
Source File: MnemonicUtils.java    From etherscan-explorer with GNU General Public License v3.0 3 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a
 * mnemonic sentence (in UTF-8 NFKD) used as the password and the string "mnemonic"
 * + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set
 * to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the
 * derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing
 *                 only valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2
 *                   function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    validateMnemonic(mnemonic);
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}
 
Example #22
Source File: MnemonicUtils.java    From client-sdk-java with Apache License 2.0 3 votes vote down vote up
/**
 * To create a binary seed from the mnemonic, we use the PBKDF2 function with a
 * mnemonic sentence (in UTF-8 NFKD) used as the password and the string "mnemonic"
 * + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set
 * to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the
 * derived key is 512 bits (= 64 bytes).
 *
 * @param mnemonic The input mnemonic which should be 128-160 bits in length containing
 *                 only valid words
 * @param passphrase The passphrase which will be used as part of salt for PBKDF2
 *                   function
 * @return Byte array representation of the generated seed
 */
public static byte[] generateSeed(String mnemonic, String passphrase) {
    if (isMnemonicEmpty(mnemonic)) {
        throw new IllegalArgumentException("Mnemonic is required to generate a seed");
    }
    passphrase = passphrase == null ? "" : passphrase;

    String salt = String.format("mnemonic%s", passphrase);
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA512Digest());
    gen.init(mnemonic.getBytes(UTF_8), salt.getBytes(UTF_8), SEED_ITERATIONS);

    return ((KeyParameter) gen.generateDerivedParameters(SEED_KEY_SIZE)).getKey();
}