List of usage examples for org.bouncycastle.crypto.paddings PaddedBufferedBlockCipher PaddedBufferedBlockCipher
public PaddedBufferedBlockCipher(BlockCipher cipher)
From source file:com.giacomodrago.immediatecrypt.aes.AESFacadeImpl.java
License:Open Source License
@Override public AESEncryptedMessage encrypt(byte[] plaintext, String password) throws EncryptionException { // Check password is not empty if (password.isEmpty()) { throw new EncryptionException("Password is empty."); }/* ww w . j av a2 s . com*/ // Generate random password salt String salt = RandomStringUtils.randomAlphanumeric(SALT_LENGTH); ParametersWithIV params = createEncryptionParameters(password, salt); byte[] iv = params.getIV(); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.init(true, params); byte[] ciphertext = new byte[cipher.getOutputSize(plaintext.length)]; int outputLen = cipher.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); try { cipher.doFinal(ciphertext, outputLen); } catch (DataLengthException ex) { throw new EncryptionException(ex); } catch (IllegalStateException ex) { throw new EncryptionException(ex); } catch (InvalidCipherTextException ex) { throw new EncryptionException(ex); } return new AESEncryptedMessage(salt, iv, ciphertext); }
From source file:com.giacomodrago.immediatecrypt.aes.AESFacadeImpl.java
License:Open Source License
@Override public byte[] decrypt(AESEncryptedMessage encryptedMessage, String password) throws EncryptionException { byte[] ciphertext = encryptedMessage.getCiphertext(); String salt = encryptedMessage.getSalt(); byte[] iv = encryptedMessage.getIv(); ParametersWithIV params = createDecryptionParameters(password, salt, iv); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); try {//from w ww. j ava 2 s . c om cipher.init(false, params); } catch (IllegalArgumentException ex) { throw new EncryptionException(ex); } byte[] plaintext = new byte[cipher.getOutputSize(ciphertext.length)]; int outputLen = cipher.processBytes(ciphertext, 0, ciphertext.length, plaintext, 0); try { cipher.doFinal(plaintext, outputLen); } catch (DataLengthException ex) { throw new EncryptionException(ex); } catch (IllegalStateException ex) { throw new EncryptionException(ex); } catch (InvalidCipherTextException ex) { throw new EncryptionException(ex); } return plaintext; }
From source file:com.google.bitcoin.crypto.KeyCrypterScrypt.java
License:MIT License
/** * Password based encryption using AES - CBC 256 bits. */// w w w .j av a 2 s . c om @Override public EncryptedPrivateKey encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException { checkNotNull(plainBytes); checkNotNull(aesKey); try { // Generate iv - each encryption call has a different iv. byte[] iv = new byte[BLOCK_LENGTH]; secureRandom.nextBytes(iv); ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv); // Encrypt using AES. BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); cipher.init(true, keyWithIv); byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)]; final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0); final int length2 = cipher.doFinal(encryptedBytes, length1); return new EncryptedPrivateKey(iv, Arrays.copyOf(encryptedBytes, length1 + length2)); } catch (Exception e) { throw new KeyCrypterException("Could not encrypt bytes.", e); } }
From source file:com.google.bitcoin.crypto.KeyCrypterScrypt.java
License:MIT License
/** * Decrypt bytes previously encrypted with this class. * * @param privateKeyToDecode The private key to decrypt * @param aesKey The AES key to use for decryption * @return The decrypted bytes * @throws KeyCrypterException if bytes could not be decoded to a valid key *///from w w w . j a v a 2 s . com @Override public byte[] decrypt(EncryptedPrivateKey privateKeyToDecode, KeyParameter aesKey) throws KeyCrypterException { checkNotNull(privateKeyToDecode); checkNotNull(aesKey); try { ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), privateKeyToDecode.getInitialisationVector()); // Decrypt the message. BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); cipher.init(false, keyWithIv); byte[] cipherBytes = privateKeyToDecode.getEncryptedBytes(); byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)]; final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0); final int length2 = cipher.doFinal(decryptedBytes, length1); return Arrays.copyOf(decryptedBytes, length1 + length2); } catch (Exception e) { throw new KeyCrypterException("Could not decrypt bytes", e); } }
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 ww .j a v a2 s . co 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 av a2s. 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.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 {/*from www . j a v a 2 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 w ww . ja va 2s . 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);// w ww . ja va 2 s.c o m }
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; }