List of usage examples for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher
public CBCBlockCipher(BlockCipher cipher)
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. 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. *///from w w w. j a va2 s. co 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:com.hanhuy.keepassj.StandardAesEngine.java
License:Open Source License
private static InputStream CreateInputStream(InputStream s, boolean bEncrypt, byte[] pbKey, byte[] pbIV) { byte[] pbLocalIV = new byte[16]; System.arraycopy(pbIV, 0, pbLocalIV, 0, 16); byte[] pbLocalKey = new byte[32]; System.arraycopy(pbKey, 0, pbLocalKey, 0, 32); try {/*w ww . ja va2 s .c o m*/ // Cipher r = Cipher.getInstance("AES/CBC/PKCS5Padding"); // IvParameterSpec ivspec = new IvParameterSpec(pbLocalIV); // SecretKeySpec keyspec = new SecretKeySpec(pbLocalKey, "AES"); // r.init(Cipher.DECRYPT_MODE, keyspec, ivspec); BlockCipher aes = AesEngines.createAesEngine(); KeyParameter key = new KeyParameter(pbLocalKey); ParametersWithIV iv = new ParametersWithIV(key, pbLocalIV); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(aes)); cipher.init(false, iv); return new CipherInputStream(s, cipher); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:com.hanhuy.keepassj.StandardAesEngine.java
License:Open Source License
private static OutputStream CreateOutputStream(OutputStream s, boolean bEncrypt, byte[] pbKey, byte[] pbIV) { byte[] pbLocalIV = new byte[16]; System.arraycopy(pbIV, 0, pbLocalIV, 0, 16); byte[] pbLocalKey = new byte[32]; System.arraycopy(pbKey, 0, pbLocalKey, 0, 32); try {/*from ww w. j a v a2 s . c o m*/ BlockCipher aes = AesEngines.createAesEngine(); KeyParameter key = new KeyParameter(pbLocalKey); ParametersWithIV iv = new ParametersWithIV(key, pbLocalIV); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(aes)); cipher.init(true, iv); // Cipher r = Cipher.getInstance("AES/CBC/PKCS5Padding"); // IvParameterSpec ivspec = new IvParameterSpec(pbLocalIV); // SecretKeySpec keyspec = new SecretKeySpec(pbLocalKey, "AES"); // r.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); return new CipherOutputStream(s, cipher); } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:com.itextpdf.kernel.crypto.AESCipher.java
License:Open Source License
/** Creates a new instance of AESCipher */ public AESCipher(boolean forEncryption, byte[] key, byte[] iv) { BlockCipher aes = new AESFastEngine(); BlockCipher cbc = new CBCBlockCipher(aes); bp = new PaddedBufferedBlockCipher(cbc); KeyParameter kp = new KeyParameter(key); ParametersWithIV piv = new ParametersWithIV(kp, iv); bp.init(forEncryption, piv);//from w w w .ja v a 2 s . c o m }
From source file:com.itextpdf.kernel.crypto.AESCipherCBCnoPad.java
License:Open Source License
/** * Creates a new instance of AESCipher// w ww . ja v a 2s .c o m */ public AESCipherCBCnoPad(boolean forEncryption, byte[] key) { BlockCipher aes = new AESFastEngine(); cbc = new CBCBlockCipher(aes); KeyParameter kp = new KeyParameter(key); cbc.init(forEncryption, kp); }
From source file:com.javacreed.api.secureproperties.bouncycastle.TwoFishCipherFactory.java
License:Apache License
@Override protected InputStream wrapInToCipheredInputStream(final InputStream in) throws Exception { final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine())); cipher.init(false, new KeyParameter(key.getBytes("UTF-8"))); final CipherInputStream stream = new CipherInputStream(in, cipher); return stream; }
From source file:com.javacreed.api.secureproperties.bouncycastle.TwoFishCipherFactory.java
License:Apache License
@Override protected OutputStream wrapInToCipheredOutputStream(final OutputStream out) throws Exception { final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new TwofishEngine())); cipher.init(true, new KeyParameter(key.getBytes("UTF-8"))); final CipherOutputStream stream = new CipherOutputStream(out, cipher); return stream; }
From source file:com.licel.jcardsim.crypto.SymmetricCipherImpl.java
License:Apache License
private void selectCipherEngine(Key theKey) { if (theKey == null) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); }// ww w. j a v a 2 s .c o m if (!theKey.isInitialized()) { CryptoException.throwIt(CryptoException.UNINITIALIZED_KEY); } if (!(theKey instanceof SymmetricKeyImpl)) { CryptoException.throwIt(CryptoException.ILLEGAL_VALUE); } SymmetricKeyImpl key = (SymmetricKeyImpl) theKey; switch (algorithm) { case ALG_DES_CBC_NOPAD: case ALG_AES_BLOCK_128_CBC_NOPAD: engine = new BufferedBlockCipher(new CBCBlockCipher(key.getCipher())); break; case ALG_DES_CBC_ISO9797_M1: engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ZeroBytePadding()); break; case ALG_DES_CBC_ISO9797_M2: engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new ISO7816d4Padding()); break; case ALG_DES_CBC_PKCS5: engine = new PaddedBufferedBlockCipher(new CBCBlockCipher(key.getCipher()), new PKCS7Padding()); break; case ALG_DES_ECB_NOPAD: case ALG_AES_BLOCK_128_ECB_NOPAD: engine = new BufferedBlockCipher(key.getCipher()); break; case ALG_DES_ECB_ISO9797_M1: engine = new PaddedBufferedBlockCipher(key.getCipher(), new ZeroBytePadding()); break; case ALG_DES_ECB_ISO9797_M2: engine = new PaddedBufferedBlockCipher(key.getCipher(), new ISO7816d4Padding()); break; case ALG_DES_ECB_PKCS5: engine = new PaddedBufferedBlockCipher(key.getCipher(), new PKCS7Padding()); break; default: CryptoException.throwIt(CryptoException.NO_SUCH_ALGORITHM); break; } }
From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java
License:Apache License
public String getAES256Cipher(String inputText, String password, boolean decrypt) { KeyIVGenerator derivedFromPassword = new KeyIVGenerator(password); // Set up key and IV these are derived from the password, using MD5 very simple. See class details. try {//from w ww . j a v a 2 s .c om byte[] buffer; //Sting to encrypt if (!decrypt) { buffer = inputText.getBytes(Charset.forName("UTF-8")); } else { buffer = Base64.decode(inputText); } // Aes Encryption BlockCipher blockCipher = new AESEngine(); // Mode CBC blockCipher = new CBCBlockCipher(blockCipher); BlockCipherPadding padding = new PKCS7Padding(); // Get our Cipher. PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, padding); // Initialize the cipher. cipher.init(!decrypt, new ParametersWithIV(new KeyParameter(derivedFromPassword.getKey()), derivedFromPassword.getIV())); //byte[] bytes_output = cipher.doFinal(buffer,0); byte bytes_output[] = new byte[cipher.getOutputSize(buffer.length)]; int len = cipher.processBytes(buffer, 0, buffer.length, bytes_output, 0); int noOfBytesCopied = cipher.doFinal(bytes_output, len); if (!decrypt) { //Return base 64 encrypted text. return new String(Base64.encode(bytes_output), Charset.forName("UTF-8")); //return Convert.ToBase64String(bytes_output, Base64FormattingOptions.InsertLineBreaks); } else { //Return plain text. return new String(bytes_output, Charset.forName("UTF-8")); } } catch (Exception e) { logger.severe(" Failure attempting to AES256 encrypt/decrypt the xml " + e.toString()); e.printStackTrace(); throw new RuntimeException(" Failure attempting AES256 " + (decrypt ? "decryption" : "encryption") + " :" + e.getMessage()); } finally { derivedFromPassword.Clean(); } }