List of usage examples for org.bouncycastle.crypto.generators PKCS5S2ParametersGenerator PKCS5S2ParametersGenerator
public PKCS5S2ParametersGenerator()
From source file:com.booleanworks.kryptopterus.entities.AppUser.java
public static byte[][] hash(String stringToHash) throws UnsupportedEncodingException { // tuning parameters // these sizes are relatively arbitrary int seedBytes = AppUser.hashAndSaltSize; int hashBytes = AppUser.hashAndSaltSize; // increase iterations as high as your performance can tolerate // since this increases computational cost of password guessing // which should help security int iterations = 1000; // to save a new password: SecureRandom rng = new SecureRandom(); byte[] salt = rng.generateSeed(seedBytes); PKCS5S2ParametersGenerator kdf = new PKCS5S2ParametersGenerator(); kdf.init(stringToHash.getBytes("UTF-8"), salt, iterations); byte[] hash = ((KeyParameter) kdf.generateDerivedMacParameters(8 * hashBytes)).getKey(); // now save salt and hash return new byte[][] { hash, salt }; }
From source file:com.booleanworks.kryptopterus.entities.AppUser.java
public static byte[][] hash(String stringToHash, byte[] sourceSalt) throws UnsupportedEncodingException { // tuning parameters // these sizes are relatively arbitrary int seedBytes = AppUser.hashAndSaltSize; int hashBytes = AppUser.hashAndSaltSize; // increase iterations as high as your performance can tolerate // since this increases computational cost of password guessing // which should help security int iterations = 1000; // to save a new password: SecureRandom rng = new SecureRandom(); byte[] salt = sourceSalt; PKCS5S2ParametersGenerator kdf = new PKCS5S2ParametersGenerator(); kdf.init(stringToHash.getBytes("UTF-8"), salt, iterations); byte[] hash = ((KeyParameter) kdf.generateDerivedMacParameters(8 * hashBytes)).getKey(); // now save salt and hash return new byte[][] { hash, salt }; }
From source file:com.booleanworks.kryptopterus.entities.AppUser.java
public static boolean checkHash(String sourceString, byte[] sourceHash, byte[] sourceSalt) throws UnsupportedEncodingException { // tuning parameters // these sizes are relatimmodificationDateodificationDatevely arbitrary int seedBytes = AppUser.hashAndSaltSize; int hashBytes = AppUser.hashAndSaltSize; // increase iterations as high as your performance can tolerate // since this increases computational cost of password guessing // which should help security int iterations = 1000; // to save a new password: SecureRandom rng = new SecureRandom(); byte[] salt = sourceSalt; PKCS5S2ParametersGenerator kdf = new PKCS5S2ParametersGenerator(); kdf.init(sourceString.getBytes("UTF-8"), salt, iterations); byte[] hash = ((KeyParameter) kdf.generateDerivedMacParameters(8 * hashBytes)).getKey(); if (hash.length != sourceHash.length) { return false; }/* w ww. j a v a 2 s . c o m*/ for (int cByte = 0; cByte < hash.length; cByte++) { if (hash[cByte] != sourceHash[cByte]) { return false; } } return true; }
From source file:com.dinochiesa.edgecallouts.util.PasswordUtil.java
License:Apache License
public static KeyAndIv deriveKeyAndIv(String plainPassword, byte[] salt, int keyBits, int ivBits, int iterations) { // Derive keys and IVs from passwords, as defined by PKCS 5 V2.0 Scheme // 2. This generator uses a SHA-1 HMac as the // calculation function. This is also known as PBKDF2, and is defined in RFC2898. // See https://en.wikipedia.org/wiki/PBKDF2 PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(); generator.init(plainPassword.getBytes(StandardCharsets.UTF_8), salt, iterations); ParametersWithIV params = (ParametersWithIV) generator.generateDerivedParameters(keyBits, ivBits); return new KeyAndIv(((KeyParameter) params.getParameters()).getKey(), params.getIV()); }
From source file:com.github.horrorho.liquiddonkey.crypto.PBKDF2.java
License:Open Source License
PBKDF2() {
this.generator = new PKCS5S2ParametersGenerator();
}
From source file:com.gpfcomics.android.cryptnos.ImportExportHandler.java
License:Open Source License
/** * Create the cipher to handle encryption and decryption for the XML-based * cross-platform file format.//from w w w. ja v a 2 s . com * @param password A String containing the password, which will be used * to derive all our encryption parameters * @param encrypt A boolean value specifying whether we should go into * encryption mode (true) or decryption mode (false) * @return A BufferedBlockCipher in the specified mode * @throws Exception Thrown whenever anything bad happens */ private static BufferedBlockCipher createXMLFormatCipher(String password, boolean encrypt, CryptnosApplication theApp) throws Exception { // I tried a dozen different things, none of which seemed to work // all that well. I finally resorted to doing everyting the Bouncy // Castle way, simply because it brought things a lot closer to being // consistent. Trying to do things entirely within .NET or Java just // wasn't cutting it. There are, however, differences between the // implementations, which are denoted below. try { // Get the password's raw bytes. Note that we're using UTF-8 here, // regardless of what the user's preferred encoding might be. byte[] pwd = password.getBytes(CryptnosApplication.TEXT_ENCODING_UTF8); byte[] salt = generateSaltFromPassword(password, theApp); // From the BC JavaDoc: "Generator for PBE derived keys and IVs as // defined by PKCS 5 V2.0 Scheme 2. This generator uses a SHA-1 // HMac as the calculation function." This is apparently a standard, // which makes my old .NET SecureFile class seem a bit embarrassing. PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(); // Initialize the generator with our password and salt. Note the // iteration count value. Examples I found around the net set this // as a hex value, but I'm not sure why advantage there is to that. // I changed it to decimal for clarity. 1000 iterations may seem // a bit excessive, and I saw some real sluggishness on the Android // emulator that could be caused by this. In the final program, // this should probably be set in a global app constant. generator.init(pwd, salt, KEY_ITERATION_COUNT); // Generate our parameters. We want to do AES-256, so we'll set // that as our key size. That also implies a 128-bit IV. Note // that the 2-int method used here is considered deprecated in the // .NET library, which could be a problem in the long term. This // is where .NET and Java diverge in BC; this is the only method // available in Java, and the comparable method is deprecated in // .NET. I'm not sure how this will work going forward. We need // to watch this, as this could be a failure point down the road. ParametersWithIV iv = ((ParametersWithIV) generator.generateDerivedParameters(KEY_SIZE, IV_SIZE)); // Create our AES (i.e. Rijndael) engine and create the actual // cipher object from it. We'll use CBC padding. RijndaelEngine engine = new RijndaelEngine(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine)); // Pick our mode, encryption or decryption: cipher.init(encrypt, iv); // Return the cipher: return cipher; } catch (Exception e) { throw e; } }
From source file:com.gpfcomics.android.ppp.PPPApplication.java
License:Open Source License
/** * Create the encryption cipher needed to securely store and retrieve encrypted * sequence keys in the database. Note that this cipher will only be created if * the user's password is set; otherwise, the cipher will default to null. *///from w w w.j a v a2 s .c om private void createCipher() { // Asbestos underpants: try { // The first thing we need to do is check to see if we have a password // set. There's no point doing anything if there's no password. String password = prefs.getString(PREF_PASSWORD, null); if (password != null) { // OK, we've got a password. Let's start by generating our salt. // To try and make this unique per device, we'll use the device's // unique ID string. To avoid the whole deprecation issue surrounding // Settings.System.ANDROID_ID vs. Settings.Secure.ANDROID_ID, we'll // wrap the call to this property inside the AndroidID class. See // that class for more details. String uniqueID = null; try { AndroidID id = AndroidID.newInstance(this); uniqueID = id.getAndroidID(); } catch (Exception e1) { } // Check the unique ID we just fetched. It's possible that we didn't // get anything useful; it's up to manufacturers to set the Android ID // property, and not everybody does it. If we didn't get anything, // we'll just make up a hard-coded random-ish string and use that as // our starting point. Of course, if we're using this, our salt will // *NOT* be unique per device, but that's the best we can do. if (uniqueID == null) uniqueID = SALT; // If we *did* get a unique ID above, go ahead and concatenate our // salt string on to the end of it as well. That should give us // a salt for our salt. else uniqueID = uniqueID.concat(SALT); // Now get the unique ID string as raw bytes. We'll use UTF-8 since // everything we get should work with that encoding. byte[] uniqueIDBytes = uniqueID.getBytes(ENCODING); // Generate our final salt value by combining the unique ID generated // above with the random salt stored in the preferences file: byte[] finalSalt = new byte[uniqueIDBytes.length + salt.length]; for (int i = 0; i < uniqueIDBytes.length; i++) { finalSalt[i] = uniqueIDBytes[i]; } for (int j = 0; j < salt.length; j++) { finalSalt[uniqueIDBytes.length + j] = salt[j]; } // Ideally, we don't want to use the raw ID by itself; that's too // easy to guess. Rather, let's hash this a few times to give us // something less predictable. MessageDigest hasher = MessageDigest.getInstance(SALT_HASH); for (int i = 0; i < KEY_ITERATION_COUNT; i++) finalSalt = hasher.digest(finalSalt); // Now, for good measure, let's obscure our password so we won't be // using the value stored in the preferences directly. We'll // concatenate the unique ID generated above into the "encrypted" // password, convert that to bytes, and hash it multiple times as // well. byte[] pwd = password.concat(uniqueID).getBytes(ENCODING); for (int i = 0; i < KEY_ITERATION_COUNT; i++) pwd = hasher.digest(pwd); // From the BC JavaDoc: "Generator for PBE derived keys and IVs as // defined by PKCS 5 V2.0 Scheme 2. This generator uses a SHA-1 // HMac as the calculation function." This is apparently a standard. PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(); // Initialize the generator with our password and salt. Note the // iteration count value. Examples I found around the Net set this // as a hex value, but I'm not sure why advantage there is to that. // I changed it to decimal for clarity. Ideally, this should be a // very large number, but experiments seem to show that setting this // too high makes the program sluggish. We'll stick to the same // key iteration count we've been using. generator.init(pwd, finalSalt, KEY_ITERATION_COUNT); // Generate our parameters. We want to do AES-256, so we'll set // that as our key size. That also implies a 128-bit IV. iv = ((ParametersWithIV) generator.generateDerivedParameters(KEY_SIZE, IV_SIZE)); // Create our AES (i.e. Rijndael) engine and create the actual // cipher object from it. We'll use CBC padding. RijndaelEngine engine = new RijndaelEngine(); cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine)); // If the password was not set, we'll null out the cipher and IV to // prevent encryption from taking place: } else { cipher = null; iv = null; } } // If anything blew up, null out the cipher and IV as well: catch (Exception e) { cipher = null; iv = null; } }
From source file:com.wlami.mibox.core.encryption.PBKDF2.java
License:Open Source License
protected static byte[] doPbkdf2(String password, String salt, int rounds) { PBEParametersGenerator pbeParametersGenerator = new PKCS5S2ParametersGenerator(); pbeParametersGenerator.init(PBEParametersGenerator.PKCS5PasswordToBytes(password.toCharArray()), PBEParametersGenerator.PKCS5PasswordToBytes(salt.toCharArray()), rounds); KeyParameter keyParameter = (KeyParameter) pbeParametersGenerator .generateDerivedParameters(DEFAULT_KEY_LENGTH_BIT); return keyParameter.getKey(); }
From source file:de.burlov.amazon.s3.dirsync.DirSync.java
License:Apache License
private byte[] generatePbeKey(char[] password) { PKCS5S2ParametersGenerator pgen = new PKCS5S2ParametersGenerator(); pgen.init(PKCS5S2ParametersGenerator.PKCS5PasswordToBytes(password), salt, ITERATION_COUNT); CipherParameters params = pgen.generateDerivedParameters(256); byte[] ret = ((KeyParameter) params).getKey(); return ret;//from ww w . java 2 s. c o m }
From source file:de.gs_sys.basics.crypto.hmac.PBKDF.java
License:Open Source License
public static byte[] bytePBKDF(String pas, int iterations) { if (pas == null) return null; PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(); // uses PKCS#5 standard generator.init(PBEParametersGenerator.PKCS5PasswordToUTF8Bytes(pas.toCharArray()), SALT, iterations); // Generate Key 32 chars at 8 bit so total 256 bit KeyParameter key = (KeyParameter) generator.generateDerivedMacParameters(KeyBitSize); return key.getKey(); }