List of usage examples for org.bouncycastle.crypto.engines AESEngine AESEngine
public AESEngine()
From source file:my.adam.smo.common.SymmetricEncryptionBox.java
License:Open Source License
public byte[] decrypt(byte[] cryptogram, byte[] key) { if (key.length != 32) { throw new IllegalArgumentException("key have to be 16 bytes long (32 bits)"); }/* w w w. j a v a2 s . co m*/ byte[] out = Arrays.copyOfRange(cryptogram, ivLength, cryptogram.length); CipherParameters cp = new ParametersWithIV(new KeyParameter(key), getIV(cryptogram)); PaddedBufferedBlockCipher descCipher; descCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); descCipher.init(false, cp); descCipher.processBytes(cryptogram, ivLength, cryptogram.length - ivLength, out, 0); return getMessageWithoutSeed(out); }
From source file:net.java.otr4j.crypto.OtrCryptoEngine.java
License:LGPL
/** * Decrypt AES-encrypted payload./* ww w .j av a2 s. c o m*/ * * @param key the decryption key * @param ctr the counter value used in encryption * @param b the ciphertext * @return Returns the decrypted content. * @throws OtrCryptoException In case of illegal ciphertext. */ @Nonnull public static byte[] aesDecrypt(final byte[] key, final byte[] ctr, final byte[] b) throws OtrCryptoException { requireLengthExactly(CTR_LENGTH_BYTES, ctr); assert !allZeroBytes( key) : "Expected non-zero bytes for key. This may indicate that a critical bug is present, or it may be a false warning."; assert !allZeroBytes( b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning."; final AESEngine aesDec = new AESEngine(); final SICBlockCipher sicAesDec = new SICBlockCipher(aesDec); final BufferedBlockCipher bufSicAesDec = new BufferedBlockCipher(sicAesDec); bufSicAesDec.init(false, new ParametersWithIV(new KeyParameter(key), ctr)); final byte[] aesOutLwDec = new byte[b.length]; final int done = bufSicAesDec.processBytes(b, 0, b.length, aesOutLwDec, 0); try { bufSicAesDec.doFinal(aesOutLwDec, done); } catch (final InvalidCipherTextException ex) { throw new OtrCryptoException("Encrypted message contents is bad.", ex); } return aesOutLwDec; }
From source file:net.java.otr4j.crypto.OtrCryptoEngine.java
License:LGPL
/** * Encrypt payload using AES./*from w w w .j av a 2 s.c o m*/ * * @param key the encryption key * @param ctr the initial counter value to use * @param b the plaintext content in bytes * @return Returns the encrypted content. */ @Nonnull public static byte[] aesEncrypt(final byte[] key, final byte[] ctr, final byte[] b) { requireLengthExactly(CTR_LENGTH_BYTES, ctr); assert !allZeroBytes( key) : "Expected non-zero bytes for key. This may indicate that a critical bug is present, or it may be a false warning."; assert !allZeroBytes( b) : "Expected non-zero bytes for b. This may indicate that a critical bug is present, or it may be a false warning."; final AESEngine aesEnc = new AESEngine(); final SICBlockCipher sicAesEnc = new SICBlockCipher(aesEnc); final BufferedBlockCipher bufSicAesEnc = new BufferedBlockCipher(sicAesEnc); bufSicAesEnc.init(true, new ParametersWithIV(new KeyParameter(key), ctr)); final byte[] aesOutLwEnc = new byte[b.length]; final int done = bufSicAesEnc.processBytes(b, 0, b.length, aesOutLwEnc, 0); try { bufSicAesEnc.doFinal(aesOutLwEnc, done); } catch (final InvalidCipherTextException ex) { throw new IllegalStateException("Failed to encrypt content.", ex); } return aesOutLwEnc; }
From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java
License:Open Source License
public static Curve25519PrivateKey deserialize(InputStream in, char[] password) throws IOException { try {//from ww w . java2 s. co m // check magic number byte[] mn = new byte[MagicNumbers.PRIVATE_KEY.length]; IOUtils.readFully(in, mn, 0, mn.length); if (!Arrays.areEqual(mn, MagicNumbers.PRIVATE_KEY)) throw new IllegalArgumentException("Wrong key file format"); // read initial vector byte[] iv = new byte[16]; IOUtils.readFully(in, iv, 0, iv.length); // read salt byte[] salt = new byte[64]; IOUtils.readFully(in, salt, 0, salt.length); // initialize cipher CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); cipher.reset(); cipher.init(false, params); // decrypt key CipherInputStream cin = new CipherInputStream(in, cipher); byte[] key = new byte[Curve25519.KEY_SIZE]; IOUtils.readFully(cin, key, 0, key.length); // return key instance return new Curve25519PrivateKey(key); } catch (UnsupportedEncodingException ex) { throw new UnsupportedOperationException(ex.getMessage(), ex); } }
From source file:net.nharyes.secrete.curve.Curve25519PrivateKey.java
License:Open Source License
public void serialize(OutputStream out, char[] password) throws IOException { try {//from w w w. j a va 2 s .co m // generate initial vector SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] iv = new byte[16]; random.nextBytes(iv); // generate salt byte[] salt = new byte[64]; random.nextBytes(salt); // initialize cipher CipherParameters params = new ParametersWithIV(new KeyParameter(deriveKey(password, salt)), iv); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding()); cipher.reset(); cipher.init(true, params); // write magic number out.write(MagicNumbers.PRIVATE_KEY); out.flush(); // write initial vector and salt out.write(iv); out.write(salt); out.flush(); // write encrypted key to output stream ByteArrayOutputStream buf = new ByteArrayOutputStream(); CipherOutputStream cout = new CipherOutputStream(buf, cipher); cout.write(key); cout.close(); out.write(buf.toByteArray()); out.flush(); } catch (UnsupportedEncodingException | NoSuchAlgorithmException ex) { throw new UnsupportedOperationException(ex.getMessage(), ex); } }
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.sourceforge.keepassj2me.datasource.HTTPConnectionThread.java
License:Open Source License
/** * Download file//from w w w . j a v a 2 s. c om * @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 ww 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.importerv3.ImporterV3.java
License:Open Source License
/** * Encrypt the master key a few times to make brute-force key-search harder * @throws NoSuchPaddingException //from w ww . jav a2 s .c o m * @throws NoSuchAlgorithmException * @throws ShortBufferException */ private byte[] transformMasterKey(byte[] pKeySeed, byte[] pKey, int rounds) /*throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, ShortBufferException*/ { // #ifdef DEBUG System.out.println("transformMasterKey, rounds=" + rounds); System.out.println("transformMasterKey, pkey=" + new String(Hex.encode(pKey))); // #endif byte[] newKey = new byte[pKey.length]; int i; BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine()); cipher.init(true, new KeyParameter(pKeySeed)); int procent = 10; //10% - progress start int step = 5;//% step int roundsByStep = rounds * step / ((90 - procent)); //90% - progress end int count = 0; newKey = pKey; for (i = 0; i < rounds; i++) { cipher.processBytes(newKey, 0, newKey.length, newKey, 0); if (++count == roundsByStep) { count = 0; setProgress(procent += step, null); } } // Hash once with SHA-256 SHA256Digest md = new SHA256Digest(); md.update(newKey, 0, newKey.length); //newKey = md.digest( newKey ); md.doFinal(newKey, 0); return newKey; }
From source file:net.sourceforge.keepassj2me.importerv3.ImporterV3.java
License:Open Source License
/** * Test Sun's JCE./*from ww w .j a va2 s. c o m*/ * Note you need the "unlimited security" policy files from Sun. * They're where you download the JDK, i.e. * <a href="http://java.sun.com/j2se/1.5.0/download.jsp" * >http://java.sun.com/j2se/1.5.0/download.jsp</a> * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException */ static void testRijndael_JCE() { byte[] aKey = new byte[32]; byte[] aTest = new byte[16]; byte[] aRef = new byte[16]; // The Rijndael class will be tested, that's the expected ciphertext int[] aRef_int = { 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 }; int i; // Do a quick test if the Rijndael class worked correctly for (i = 0; i < 32; i++) { aKey[i] = (byte) i; } for (i = 0; i < 16; i++) { aTest[i] = (byte) ((i << 4) | i); aRef[i] = (byte) aRef_int[i]; } try { // Cipher cipher = Cipher.getInstance( "AES/ECB/NoPadding" ); BufferedBlockCipher cipher = new BufferedBlockCipher(new AESEngine()); //cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec( aKey, "AES" ) ); cipher.init(true, new KeyParameter(aKey)); //aTest = cipher.doFinal( aTest ); cipher.processBytes(aTest, 0, aTest.length, aTest, 0); } catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException("JCE failed test"); } if (Util.compare(aTest, aRef) == false) throw new RuntimeException("JCE failed test"); }