List of usage examples for org.bouncycastle.crypto.modes CBCBlockCipher CBCBlockCipher
public CBCBlockCipher(BlockCipher cipher)
From source file:net.nharyes.secrete.ecies.ECIES.java
License:Open Source License
private static IESEngine getIESEngine() { return new IESEngine(new Curve25519Agreement(), new KDF2BytesGenerator(new SHA512Digest()), new HMac(new SHA512Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding())); }
From source file:net.sf.jsignpdf.JSignEncryptor.java
License:Mozilla Public License
/** * Initialize the cryptographic engine./*from w ww .java 2 s .com*/ * * @param aKey */ public JSignEncryptor(final byte[] aKey) { cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new BlowfishEngine())); key = new KeyParameter(aKey); }
From source file:net.sourceforge.keepassj2me.datasource.HTTPConnectionThread.java
License:Open Source License
/** * Download file/* ww w .j av a 2 s .c o m*/ * @param url Site URL * @param userCode User login * @param passCode User password * @param encCode * @param form UI to display download progress * @throws IOException * @throws RecordStoreException * @throws KeePassException */ private void connect(String url, String userCode, String passCode, String encCode, Form form) throws IOException, KeePassException { // #ifdef DEBUG System.out.println("connect: 1"); // #endif HttpConnection hc = null; InputStream in = null; String rawData = "usercode=" + userCode + "&passcode=" + passCode; String type = "application/x-www-form-urlencoded"; hc = (HttpConnection) Connector.open(url); hc.setRequestMethod(HttpConnection.POST); hc.setRequestProperty("Content-Type", type); hc.setRequestProperty("Content-Length", "13"); // #ifdef DEBUG System.out.println("connect: 2"); // #endif OutputStream os = hc.openOutputStream(); os.write(rawData.getBytes()); int rc = hc.getResponseCode(); // #ifdef DEBUG System.out.println("rc = " + rc); // #endif if (rc != HttpConnection.HTTP_OK) { throw new IOException("HTTP response code: " + rc); } // #ifdef DEBUG System.out.println("connect: 3"); // #endif in = hc.openInputStream(); int contentLength = (int) hc.getLength(); content = null; if (contentLength > 0) { // length available // #ifdef DEBUG System.out.println("connect: 4, contentLength = " + contentLength); // #endif content = new byte[contentLength]; in.read(content); } else { // length not available // #ifdef DEBUG System.out.println("connect: 5, contentLength not known"); // #endif //int data; content = null; final int BUFLEN = 1024; int readLen; contentLength = 0; while (true) { byte[] newContent = new byte[contentLength + BUFLEN]; if (contentLength > 0) System.arraycopy(content, 0, newContent, 0, contentLength); readLen = in.read(newContent, contentLength, BUFLEN); content = newContent; contentLength += readLen; form.append("read: " + readLen + " bytes\r\n"); // #ifdef DEBUG System.out.println("read: " + readLen + " bytes"); // #endif if (readLen < BUFLEN) break; } } in.close(); hc.close(); // Show the response to the user. // #ifdef DEBUG System.out.println("Downloaded " + contentLength + " bytes"); // #endif form.append("Downloaded " + contentLength + " bytes\r\n"); if (contentLength - HTTPConnectionThread.KDB_HEADER_LEN <= 0 || (contentLength - HTTPConnectionThread.KDB_HEADER_LEN) % 16 != 0) { form.append( "Wrong KDB length ... Download failed because KDB file is not on the server, network error, wrong username, or wrong passcode.\r\n"); throw new IOException( "Wrong KDB length ... Download failed because KDB file is not on the server, network error, wrong username, or wrong passcode."); } form.append("Generating encryption key ...\r\n"); // decrypt KDB with enc code byte[] encKey = passwordKeySHA(encCode); form.append("Decrypting KDB ...\r\n"); BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.init(false, new ParametersWithIV(new KeyParameter(encKey), HTTPConnectionThread.ZeroIV)); // #ifdef DEBUG int outlen = // #endif cipher.getOutputSize(contentLength - HTTPConnectionThread.KDB_HEADER_LEN); // #ifdef DEBUG System.out.println("Output size: " + outlen); // #endif // #ifdef DEBUG int size = // #endif cipher.processBytes(content, HTTPConnectionThread.KDB_HEADER_LEN, contentLength - HTTPConnectionThread.KDB_HEADER_LEN, content, HTTPConnectionThread.KDB_HEADER_LEN); // #ifdef DEBUG System.out.println("KDB decrypted length: " + size); // #endif }
From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java
License:Open Source License
/** * Load a v3 database file, return contents in a new PwManager. * /*from w w w . j a v a 2s.c o m*/ * @param infile Existing file to load. * @param password Pass phrase for infile. * @param pRepair (unused) * @return new PwManager container. * * @throws IOException on any file error. * @throws InvalidKeyException on a decryption error, or possible internal bug. * @throws IllegalBlockSizeException on a decryption error, or possible internal bug. * @throws BadPaddingException on a decryption error, or possible internal bug. * @throws NoSuchAlgorithmException on a decryption error, or possible internal bug. * @throws NoSuchPaddingException on a decryption error, or possible internal bug. * @throws InvalidAlgorithmParameterException if error decrypting main file body. * @throws ShortBufferException if error decrypting main file body. */ public PwManager openDatabase(InputStream inStream, String password) throws IOException, InvalidCipherTextException, Exception { PwManager newManager; SHA256Digest md; /** Master key encrypted several times */ byte[] transformedMasterKey; byte[] finalKey; setProgress(5, "Open database"); // #ifdef DEBUG System.out.println("Open database"); // #endif // Load entire file, most of it's encrypted. // InputStream in = new FileInputStream( infile ); byte[] filebuf = new byte[(int) inStream.available()]; inStream.read(filebuf, 0, (int) inStream.available()); inStream.close(); // Parse header (unencrypted) if (filebuf.length < PwDbHeader.BUF_SIZE) throw new IOException("File too short for header"); PwDbHeader hdr = new PwDbHeader(filebuf, 0); if ((hdr.signature1 != PwManager.PWM_DBSIG_1) || (hdr.signature2 != PwManager.PWM_DBSIG_2)) { // #ifdef DEBUG System.out.println("Bad database file signature"); // #endif throw new IOException("Bad database file signature"); } if (hdr.version != PwManager.PWM_DBVER_DW) { // #ifdef DEBUG System.out.println("Bad database file version"); // #endif throw new IOException("Bad database file version"); } newManager = new PwManager(); newManager.setMasterKey(password); // Select algorithm if ((hdr.flags & PwManager.PWM_FLAG_RIJNDAEL) != 0) { // #ifdef DEBUG System.out.println("Algorithm AES"); // #endif newManager.algorithm = PwManager.ALGO_AES; } else if ((hdr.flags & PwManager.PWM_FLAG_TWOFISH) != 0) { // #ifdef DEBUG System.out.println("Algorithm TWOFISH"); // #endif newManager.algorithm = PwManager.ALGO_TWOFISH; } else { throw new IOException("Unknown algorithm."); } if (newManager.algorithm == PwManager.ALGO_TWOFISH) throw new IOException("TwoFish algorithm is not supported"); newManager.numKeyEncRounds = hdr.numKeyEncRounds; // #ifdef DEBUG System.out.println("rounds = " + newManager.numKeyEncRounds); // #endif // testRijndael_JCE(); newManager.name = "KeePass Password Manager"; // Generate transformedMasterKey from masterKey //KeePassMIDlet.logS ("masterSeed2: " + new String(Hex.encode(hdr.masterSeed2))); setProgress(10, "Decrypt key"); transformedMasterKey = transformMasterKey(hdr.masterSeed2, newManager.masterKey, newManager.numKeyEncRounds); // Hash the master password with the salt in the file md = new SHA256Digest(); md.update(hdr.masterSeed, 0, hdr.masterSeed.length); md.update(transformedMasterKey, 0, transformedMasterKey.length); finalKey = new byte[md.getDigestSize()]; md.doFinal(finalKey, 0); setProgress(90, "Decrypt database"); // NI //KeePassMIDlet.logS ("finalKey: " + new String(Hex.encode(finalKey))); // Initialize Rijndael algorithm // Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS5Padding" ); //PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine())); BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); //cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( finalKey, "AES" ), new IvParameterSpec( hdr.encryptionIV ) ); cipher.init(false, new ParametersWithIV(new KeyParameter(finalKey), hdr.encryptionIV)); // Decrypt! The first bytes aren't encrypted (that's the header) //int encryptedPartSize = cipher.doFinal( filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE ); //int encryptedPartSize int paddedEncryptedPartSize = cipher.processBytes(filebuf, PwDbHeader.BUF_SIZE, filebuf.length - PwDbHeader.BUF_SIZE, filebuf, PwDbHeader.BUF_SIZE); int encryptedPartSize = 0; //try { PKCS7Padding padding = new PKCS7Padding(); encryptedPartSize = paddedEncryptedPartSize - padding.padCount(filebuf); //} catch (Exception e) { //} // NI byte[] plainContent = new byte[encryptedPartSize]; System.arraycopy(filebuf, PwDbHeader.BUF_SIZE, plainContent, 0, encryptedPartSize); // #ifdef DEBUG System.out.println("filebuf length: " + filebuf.length); // #endif //System.out.println ("file length: " + filebuf.length); //System.out.println ("plaintext contents length: " + encryptedPartSize); //System.out.println ("plaintext contents:\n" + new String(Hex.encode(plainContent))); //if( pRepair == null ) { //md = MessageDigest.getInstance( "SHA-256" ); md = new SHA256Digest(); md.update(filebuf, PwDbHeader.BUF_SIZE, encryptedPartSize); // md.update( makePad(filebuf) ); md.doFinal(finalKey, 0); if (Util.compare(finalKey, hdr.contentsHash) == false) { //KeePassMIDlet.logS ( "Database file did not decrypt correctly. (checksum code is broken)" ); // #ifdef DEBUG System.out.println("Database file did not decrypt correctly. (checksum code is broken)"); // #endif throw new Exception( "Wrong Password, or Database File Corrupted (database file did not decrypt correctly)"); } // } setProgress(95, "Import groups"); // Import all groups // #ifdef DEBUG System.out.println("Import all groups"); // #endif int pos = PwDbHeader.BUF_SIZE; PwGroup newGrp = new PwGroup(); for (int i = 0; i < hdr.numGroups;) { int fieldType = Types.readShort(filebuf, pos); pos += 2; int fieldSize = Types.readInt(filebuf, pos); pos += 4; if (fieldType == 0xFFFF) { // #ifdef DEBUG System.out.println(newGrp.level + " " + newGrp.name); // #endif // End-Group record. Save group and count it. //newManager.groups.add( newGrp ); newManager.addGroup(newGrp); newGrp = new PwGroup(); i++; } else { readGroupField(newGrp, fieldType, filebuf, pos); } pos += fieldSize; } // fixGroups( groups ); setProgress(97, "Import entries"); // Import all entries // #ifdef DEBUG System.out.println("Import all entries"); // #endif PwEntry newEnt = new PwEntry(); for (int i = 0; i < hdr.numEntries;) { int fieldType = Types.readShort(filebuf, pos); int fieldSize = Types.readInt(filebuf, pos + 2); if (fieldType == 0xFFFF) { // End-Group record. Save group and count it. newManager.addEntry(newEnt); // #ifdef DEBUG System.out.println(newEnt.title); // #endif newEnt = new PwEntry(); i++; } else { readEntryField(newEnt, filebuf, pos); } pos += 2 + 4 + fieldSize; } // Keep the Meta-Info entry separate // #ifdef DEBUG System.out.println("Keep the Meta-Info entry separate"); // #endif for (int i = 0; i < newManager.entries.size(); i++) { PwEntry ent = (PwEntry) newManager.entries.elementAt(i); if (ent.title.equals("Meta-Info") && ent.url.equals("$") && ent.username.equals("SYSTEM")) { newManager.metaInfo = ent; newManager.entries.removeElementAt(i); } } setProgress(100, "Done"); // #ifdef DEBUG System.out.println("Return newManager: " + newManager); // #endif return newManager; }
From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java
License:Open Source License
/** * Encode database/*w w w . java 2 s.c om*/ * @return encoded database * @throws KeydbException */ public byte[] getEncoded() throws KeydbException {//Encrypt content if (isLocked()) return this.encodedContent; if ((this.header.numGroups == 0) && (this.header.numEntries == 0)) throw new KeydbException(Config.getLocaleString(keys.KD_NOTHING_SAVE)); BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); //calc padding size int block_size = cipher.getBlockSize(); int pad_size = block_size - this.contentSize % block_size; // #ifdef DEBUG System.out.println("contentSize: " + this.contentSize); System.out.println("block_size: " + block_size); System.out.println("pad_size: " + pad_size); // #endif //add padding to content byte temp[] = new byte[this.contentSize + pad_size]; System.arraycopy(this.plainContent, 0, temp, 0, this.contentSize); KeydbUtil.fill(this.plainContent, (byte) 0); this.plainContent = temp; temp = null; PKCS7Padding padding = new PKCS7Padding(); padding.addPadding(this.plainContent, this.contentSize); byte encoded[] = new byte[KeydbHeader.SIZE + this.contentSize + pad_size]; //encode cipher.init(true, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV)); int paddedEncryptedPartSize = cipher.processBytes(this.plainContent, 0, this.plainContent.length, encoded, KeydbHeader.SIZE); if (paddedEncryptedPartSize != this.plainContent.length) { // #ifdef DEBUG System.out.println("Encoding: " + paddedEncryptedPartSize + " != " + this.plainContent.length); // #endif throw new KeydbException(Config.getLocaleString(keys.KD_ENCRYPTING_FAILED)); } //Set header this.header.contentsHash = KeydbUtil.hash(this.plainContent, 0, this.contentSize); this.header.write(encoded, 0); return encoded; }
From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java
License:Open Source License
private void decrypt(byte[] encoded, int offset, int length) throws KeydbException { BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); cipher.init(false, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV)); // Decrypt! The first bytes aren't encrypted (that's the header) this.plainContent = new byte[encoded.length - KeydbHeader.SIZE]; int paddedEncryptedPartSize = cipher.processBytes(encoded, offset, length, this.plainContent, 0); //detect padding and calc content size this.contentSize = 0; PKCS7Padding padding = new PKCS7Padding(); try {/*w w w.j a v a2 s . c om*/ this.contentSize = paddedEncryptedPartSize - padding.padCount(this.plainContent); } catch (InvalidCipherTextException e) { throw new KeydbException(Config.getLocaleString(keys.KD_DB_DECRYPT_ERR, new String[] { "1" })); } if (!KeydbUtil.compare(KeydbUtil.hash(this.plainContent, 0, this.contentSize), this.header.contentsHash)) { throw new KeydbException(Config.getLocaleString(keys.KD_DB_DECRYPT_ERR, new String[] { "2" })); } }
From source file:org.albertschmitt.crypto.AESService.java
License:Open Source License
/** * Return a PaddedBufferedBlockCipher for encryption or decryption. * * @param iv The initialization vector./*from w w w . j a v a 2s . c o m*/ * @param forEncryption True to encrypt, false to decrypt. * @return PaddedBufferedBlockCipher configured to encrypt or decrypt. */ private PaddedBufferedBlockCipher getCipher(byte[] iv, Boolean forEncryption) { ParametersWithIV ivKeyParam = new ParametersWithIV(aes_key, iv); BlockCipherPadding padding = new PKCS7Padding(); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding); cipher.reset(); cipher.init(forEncryption, ivKeyParam); return cipher; }
From source file:org.bigmouth.nvwa.utils.degist.AesUtils.java
License:Apache License
/** * Encrypt data.// w w w . j a va2s . c o m * * @param plain * @param key * @param iv * @return * @throws Exception */ public static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); return cipherData(aes, plain); }
From source file:org.bigmouth.nvwa.utils.degist.AesUtils.java
License:Apache License
/** * Decrypt data./*from w w w .j a va 2 s . c om*/ * * @param cipher * @param key * @param iv * @return * @throws Exception */ public static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); return cipherData(aes, cipher); }
From source file:org.cryptacular.pbe.PBES2EncryptionScheme.java
License:Open Source License
/** * Initializes the block cipher and sets up its initialization parameters. * * @param generator Derived key generator. * @param scheme PKCS#5 encryption scheme. *///from w w w.ja v a2 s .c om private void initCipher(final PKCS5S2ParametersGenerator generator, final org.bouncycastle.asn1.pkcs.EncryptionScheme scheme) { final PBES2Algorithm alg = PBES2Algorithm.fromOid(scheme.getAlgorithm().getId()); if (keyLength == 0) { keyLength = alg.getKeySize(); } byte[] iv = null; CipherParameters cipherParameters = generator.generateDerivedParameters(keyLength); switch (alg) { case RC2: setCipher(alg.getCipherSpec().newInstance()); final ASN1Sequence rc2Params = ASN1Sequence.getInstance(scheme.getParameters()); if (rc2Params.size() > 1) { cipherParameters = new RC2Parameters(((KeyParameter) cipherParameters).getKey(), ASN1Integer.getInstance(rc2Params.getObjectAt(0)).getValue().intValue()); iv = ASN1OctetString.getInstance(rc2Params.getObjectAt(0)).getOctets(); } break; case RC5: final ASN1Sequence rc5Params = ASN1Sequence.getInstance(scheme.getParameters()); final int rounds = ASN1Integer.getInstance(rc5Params.getObjectAt(1)).getValue().intValue(); final int blockSize = ASN1Integer.getInstance(rc5Params.getObjectAt(2)).getValue().intValue(); if (blockSize == 32) { setCipher(new PaddedBufferedBlockCipher(new CBCBlockCipher(new RC532Engine()), new PKCS7Padding())); } cipherParameters = new RC5Parameters(((KeyParameter) cipherParameters).getKey(), rounds); if (rc5Params.size() > 3) { iv = ASN1OctetString.getInstance(rc5Params.getObjectAt(3)).getOctets(); } break; default: setCipher(alg.getCipherSpec().newInstance()); iv = ASN1OctetString.getInstance(scheme.getParameters()).getOctets(); } if (iv != null) { cipherParameters = new ParametersWithIV(cipherParameters, iv); } setCipherParameters(cipherParameters); }