List of usage examples for org.bouncycastle.crypto.generators PKCS5S2ParametersGenerator generateDerivedParameters
public CipherParameters generateDerivedParameters(int keySize, int ivSize)
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.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 ww w. ja v a 2 s .c o m * @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. *//* ww w. j ava 2 s. c o m*/ 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:org.bunkr.core.descriptor.PBKDF2Descriptor.java
License:Open Source License
@Override public Inventory readInventoryFromBytes(byte[] source, UserSecurityProvider usp) throws BaseBunkrException { try {/*from w ww.j a v a 2 s . co m*/ if (this.encryptionAlgorithm == Encryption.NONE) throw new IllegalArgumentException("PBKDF2Descriptor requires an active encryption mode"); PKCS5S2ParametersGenerator g = new PKCS5S2ParametersGenerator(new SHA256Digest()); g.init(usp.getHashedPassword(), this.pbkdf2Salt, this.pbkdf2Iterations); ParametersWithIV kp = (ParametersWithIV) g.generateDerivedParameters( this.encryptionAlgorithm.keyByteLength * 8, this.encryptionAlgorithm.ivByteLength * 8); byte[] decryptedInv = SimpleAES.decrypt(this.encryptionAlgorithm, source, ((KeyParameter) kp.getParameters()).getKey(), kp.getIV()); return InventoryJSON.decode(new String(decryptedInv)); } catch (IllegalPasswordException | CryptoException e) { throw new BaseBunkrException(e); } }
From source file:org.bunkr.core.descriptor.PBKDF2Descriptor.java
License:Open Source License
@Override public byte[] writeInventoryToBytes(Inventory source, UserSecurityProvider usp) throws BaseBunkrException { try {/* www. j av a 2 s . com*/ byte[] inventoryJsonBytes = InventoryJSON.encode(source).getBytes(); if (this.encryptionAlgorithm == Encryption.NONE) throw new IllegalArgumentException("PBKDF2Descriptor requires an active encryption mode"); // first refresh the salt RandomMaker.fill(this.pbkdf2Salt); PKCS5S2ParametersGenerator g = new PKCS5S2ParametersGenerator(new SHA256Digest()); g.init(usp.getHashedPassword(), this.pbkdf2Salt, this.pbkdf2Iterations); ParametersWithIV kp = (ParametersWithIV) g.generateDerivedParameters( this.encryptionAlgorithm.keyByteLength * 8, this.encryptionAlgorithm.ivByteLength * 8); // encrypt the inventory byte[] encryptedInv = SimpleAES.encrypt(this.encryptionAlgorithm, inventoryJsonBytes, ((KeyParameter) kp.getParameters()).getKey(), kp.getIV()); Arrays.fill(inventoryJsonBytes, (byte) 0); return encryptedInv; } catch (IllegalPasswordException | CryptoException e) { throw new BaseBunkrException(e); } }