Example usage for org.bouncycastle.crypto.engines BlowfishEngine BlowfishEngine

List of usage examples for org.bouncycastle.crypto.engines BlowfishEngine BlowfishEngine

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.engines BlowfishEngine BlowfishEngine.

Prototype

public BlowfishEngine() 

Source Link

Usage

From source file:cc.agentx.security.BlowfishCipher.java

License:Apache License

/**
 * <b>Notice: </b><br/>
 * 1. in <code>new CFBBlockCipher(engine, <b>8</b> * 8);</code> the IV length (8) is
 * reference to the shadowsocks's design.
 *
 * @see <a href="https://shadowsocks.org/en/spec/cipher.html">
 * https://shadowsocks.org/en/spec/cipher.html</a>#Cipher
 *//*from  www  .  j a  va2s . c  om*/
public BlowfishCipher(String password, int mode) {
    key = new SecretKeySpec(password.getBytes(), "BF");
    keyLength = mode;
    BlowfishEngine engine = new BlowfishEngine();
    cipher = new CFBBlockCipher(engine, 8 * 8);
}

From source file:cologne.eck.dr.op.crypto.password_hashing.Battcrypt_v0.java

License:Open Source License

@Override
public byte[] hashPassword(int outlen, byte[] in, byte[] salt, int t_cost, int m_cost, Object... varArgs)
        throws DataLengthException, IllegalStateException, InvalidCipherTextException {

    SHA512Digest sha = new SHA512Digest();
    int[] data = new int[DATA_SIZE_INT];
    BlowfishEngine blowfish;//  w ww  . j  ava2 s  .  co m
    long upgradeLoops = 1;
    long loops;
    int memSize = 4 << m_cost;//= 4 * 2 ** m_cost
    int memMask = memSize - 1;
    int[] mem;

    byte[] hashBuffer = new byte[HASH_LENGTH_BYTE];// holds hash value as bytes
    byte[] dataBuffer = new byte[DATA_SIZE_BYTE];// holds encrypted bytes

    // These are the PHP max. values 
    if (m_cost > 18 || // maximum: 2.147.483.648 bytes
            (t_cost & 0xffff) > 62 || (t_cost >> 16) > 63 || outlen > HASH_LENGTH_BYTE) {
        throw new IllegalArgumentException("invalid parameters");
    }

    int tmp = t_cost >> 16;

    if (tmp != 0) {
        // upgradeLoops = 1, 2, 3, 4, 6, 8, 12, 16, ...
        upgradeLoops = (long) (3 - (tmp & 1)) << ((tmp - 1) >> 1);
    }

    // loops = 2, 3, 4, 6, 8, 12, 16, ...
    tmp = t_cost & 0xffff;
    loops = (long) ((tmp & 1) + 2) << (tmp >> 1);

    // key = SHA512(SHA512(salt) || in)
    byte[] keyBytes = new byte[HASH_LENGTH_BYTE];
    sha.update(salt, 0, salt.length);
    sha.doFinal(keyBytes, 0);
    sha.reset();
    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.update(in, 0, in.length);//password
    sha.doFinal(keyBytes, 0);
    sha.reset();
    if (wipePassword == true) {
        Arrays.fill(in, (byte) 0);
    }

    // initialize cipher with 448 bit (56 byte) key: 
    // truncate keyBytes:
    byte[] blowfishKey = new byte[56];
    System.arraycopy(keyBytes, 0, blowfishKey, 0, 56);
    // use zeros as IV
    byte[] iv = new byte[IV_LENGTH_BYTE];
    KeyParameter params = new KeyParameter(blowfishKey);
    Arrays.fill(blowfishKey, (byte) 0);
    ParametersWithIV ivParams = new ParametersWithIV(params, iv);
    blowfish = new BlowfishEngine();
    // CBC, no padding: all vectors are multiples of Blowfish block length
    BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(blowfish));
    cipher.init(true, ivParams);

    // initialize memory-hard vector:
    mem = new int[DATA_SIZE_INT * memSize];

    for (long u = 0; u < upgradeLoops; u++) {

        // initialize data:
        // data = SHA512(BIG_ENDIAN_64( 0) || key) || ...
        // ... || SHA512(BIG_ENDIAN_64(31) || key)         
        byte[] counterBytesBE = new byte[8]; // holds counter as long to update
        for (int i = 0; i < DATA_SIZE_BYTE / HASH_LENGTH_BYTE; i++) {

            counterBytesBE[7] = (byte) i; // set first byte
            sha.update(counterBytesBE, 0, counterBytesBE.length); // BIG_ENDIAN_64(i)
            sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
            sha.doFinal(hashBuffer, 0);
            sha.reset();
            // hash values allow weak garbage collector attack - 
            // so, avoid new allocations:             
            for (int j = 0; j < HASH_LENGTH_BYTE / 4; j++) {
                data[HASH_LENGTH_INT * i + j] = ((hashBuffer[j * 4 + 3] & 0xFF) << 24)
                        | ((hashBuffer[j * 4 + 2] & 0xFF) << 16) | ((hashBuffer[j * 4 + 1] & 0xFF) << 8)
                        | (hashBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            Arrays.fill(hashBuffer, (byte) 0);
        }

        // Initialize memory:
        for (int i = 0; i < memSize; i++) {
            // data = blowfish_encrypt_cbc(data)
            // mem = mem || data            
            for (int j = 0; j < DATA_SIZE_INT; j++) {
                dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
                dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
                dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
                dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
            }
            int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
            cipher.doFinal(dataBuffer, len);
            cipher.reset();

            // get iv for next encryption step:
            // "running CBC": the last block of the
            //  previous call is the IV for the next call
            System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
            ivParams = new ParametersWithIV(params, iv);
            cipher.init(true, ivParams);

            for (int j = 0; j < DATA_SIZE_INT; j++) {
                data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                        | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
            }
            System.arraycopy(data, 0, mem, DATA_SIZE_INT * i, DATA_SIZE_INT);
        }

        // encrypt data:
        for (int j = 0; j < DATA_SIZE_INT; j++) {
            dataBuffer[j * 4 + 0] = (byte) (data[j]);// little endian
            dataBuffer[j * 4 + 1] = (byte) (data[j] >>> 8);
            dataBuffer[j * 4 + 2] = (byte) (data[j] >>> 16);
            dataBuffer[j * 4 + 3] = (byte) (data[j] >>> 24);
        }
        int len = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);
        cipher.doFinal(dataBuffer, len);
        cipher.reset();
        System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);
        ivParams = new ParametersWithIV(params, iv);
        cipher.init(true, ivParams);

        for (int j = 0; j < DATA_SIZE_INT; j++) {
            data[j] = ((dataBuffer[j * 4 + 3] & 0xFF) << 24) | ((dataBuffer[j * 4 + 2] & 0xFF) << 16)
                    | ((dataBuffer[j * 4 + 1] & 0xFF) << 8) | (dataBuffer[j * 4 + 0] & 0xFF); // little endian order
        }

        // work:
        for (long i = 0; i < loops; i++) {
            for (int j = 0; j < memSize; j++) {
                // in the C++ reference implementation and the paper 
                // this rValue a 64 bit integer, but this makes only a
                // difference for memSize > 0xFFFFFFFF +1, while the
                // recommended maximum for memSize is 2^32
                int rValue = ((((int) data[DATA_SIZE_INT - 1]) << 24) & 0xff000000)
                        | ((((int) data[DATA_SIZE_INT - 1]) << 8) & 0x00ff0000)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 8) & 0x0000ff00)
                        | ((((int) data[DATA_SIZE_INT - 1]) >>> 24) & 0x000000ff);
                int index = (int) (DATA_SIZE_INT * (rValue & memMask));

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] ^= data[k] ^ mem[index + k];
                }

                // convert to byte: 
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    dataBuffer[k * 4 + 0] = (byte) (mem[j * DATA_SIZE_INT + k]);
                    dataBuffer[k * 4 + 1] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 8);
                    dataBuffer[k * 4 + 2] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 16);
                    dataBuffer[k * 4 + 3] = (byte) (mem[j * DATA_SIZE_INT + k] >>> 24);
                }
                int len1 = cipher.processBytes(dataBuffer, 0, DATA_SIZE_BYTE, dataBuffer, 0);

                cipher.doFinal(dataBuffer, len1);
                cipher.reset();
                // get iv for next step:
                System.arraycopy(dataBuffer, DATA_SIZE_BYTE - IV_LENGTH_BYTE, iv, 0, IV_LENGTH_BYTE);

                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    mem[j * DATA_SIZE_INT + k] = ((dataBuffer[k * 4 + 3] & 0xFF) << 24)
                            | ((dataBuffer[k * 4 + 2] & 0xFF) << 16) | ((dataBuffer[k * 4 + 1] & 0xFF) << 8)
                            | (dataBuffer[k * 4 + 0] & 0xFF); // little endian order
                }

                ivParams = new ParametersWithIV(params, iv);
                cipher.init(true, ivParams);

                // data ^= mem[j]
                for (int k = 0; k < DATA_SIZE_INT; k++) {
                    data[k] ^= mem[DATA_SIZE_INT * j + k];
                }
            }
        }
        // Finish
        // key = truncate(SHA512(SHA512(data || key)), outlen) || zeros(HASH_LENGTH - outlen)
        // convert to byte: 
        for (int k = 0; k < DATA_SIZE_INT; k++) {
            dataBuffer[k * 4 + 0] = (byte) (data[k]);
            dataBuffer[k * 4 + 1] = (byte) (data[k] >>> 8);
            dataBuffer[k * 4 + 2] = (byte) (data[k] >>> 16);
            dataBuffer[k * 4 + 3] = (byte) (data[k] >>> 24);
        }
        sha.update(dataBuffer, 0, DATA_SIZE_BYTE);
        sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
        sha.doFinal(keyBytes, 0);
        sha.reset();
    }

    sha.update(keyBytes, 0, HASH_LENGTH_BYTE);
    sha.doFinal(keyBytes, 0);
    sha.reset();

    byte[] out = new byte[outlen];

    System.arraycopy(keyBytes, 0, out, 0, out.length);

    // Clean-up:
    Arrays.fill(keyBytes, (byte) 0);
    Arrays.fill(dataBuffer, (byte) 0);
    Arrays.fill(iv, (byte) 0);
    Arrays.fill(data, 0);
    Arrays.fill(mem, (byte) 0);

    // wipe the key from parameters
    Arrays.fill(params.getKey(), (byte) 0);

    // prevent dead code eliminations (compiler optimizations):
    if ((keyBytes[HASH_LENGTH_BYTE - 1] | blowfishKey[blowfishKey.length - 1] | dataBuffer[DATA_SIZE_BYTE - 1]
            | hashBuffer[HASH_LENGTH_BYTE - 1] | data[DATA_SIZE_INT - 1] | iv[IV_LENGTH_BYTE - 1]
            | mem[mem.length - 1] | params.getKey()[params.getKey().length - 1]) != 0) {
        System.err.print("zeroization failed!");
    }
    if ((wipePassword == true) && (in[in.length - 1] != 0)) {
        System.err.print("zeroization failed!");
    }
    return out;
}

From source file:com.googlecode.jsendnsca.encryption.BlowfishEncryptor.java

License:Apache License

@Override
public void encrypt(final byte[] passiveCheckBytes, final byte[] initVector, final String password) {

    final BlowfishEngine engine = new BlowfishEngine();
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CFBBlockCipher(engine, 8),
            new ZeroBytePadding());

    try {//from www .j  a  va 2 s . c o m
        final byte[] passwordBytes = password.getBytes("US-ASCII");

        assertValidPasswordBytesLength(passwordBytes);

        final byte[] sessionKey = new byte[KEY_BYTES_LENGTH];
        System.arraycopy(passwordBytes, 0, sessionKey, 0, Math.min(KEY_BYTES_LENGTH, passwordBytes.length));

        final byte[] iv = new byte[KEY_BYTES_LENGTH];
        System.arraycopy(initVector, 0, iv, 0, Math.min(KEY_BYTES_LENGTH, initVector.length));

        cipher.init(true, new ParametersWithIV(new KeyParameter(sessionKey), iv));

        final byte[] cipherText = new byte[cipher.getOutputSize(passiveCheckBytes.length)];
        int cipherLength = cipher.processBytes(passiveCheckBytes, 0, passiveCheckBytes.length, cipherText, 0);
        cipherLength = cipherLength + cipher.doFinal(cipherText, cipherLength);

        final int bytesToCopy = Math.min(passiveCheckBytes.length, cipherLength);
        System.arraycopy(cipherText, 0, passiveCheckBytes, 0, bytesToCopy);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:crypto.util.encription.Crypto.java

public Crypto(byte[] key) {
    /*/*from   w w  w. j  a v  a  2  s.  com*/
     cipher = new PaddedBlockCipher(
     new CBCBlockCipher(
     new DESEngine() ) );
     */

    cipher = new PaddedBlockCipher(new CBCBlockCipher(new BlowfishEngine()));

    this.key = new KeyParameter(key);
}

From source file:de.gs_sys.kp2016.crypto.SymmetricCipher.java

License:Open Source License

public static void setEngine(ENGINE e) {
    activeEngine = e;//from  w  w w.  j  av a 2s  . c o m
    switch (e) {
    case AES:
        engine = new AESEngine();
        break;
    //    case AES_WRAP:
    //        engine = new AESWrapEngine();
    //        break;
    case Rijndael:
        engine = new RijndaelEngine();
        break;
    case Camellia:
        engine = new CamelliaEngine();
        break;
    case Blowfish:
        engine = new BlowfishEngine();
        break;
    case Serpent:
        engine = new SerpentEngine();
        break;
    case Threefish:
        //engine = new ThreefishEngine(256);
        engine = new ThreefishEngine(ThreefishSize);
        break;
    case Twofish:
    default:
        engine = new TwofishEngine();
    }
}

From source file:de.gs_sys.kp2016.crypto.SymmetricCipher.java

License:Open Source License

@Deprecated
protected static BlockCipher getEngine(ENGINE engine) {
    switch (engine) {
    case AES://from   w w w.  j a v  a2  s  .co  m
        return new AESEngine();
    //    case AES_WRAP:
    //        return new AESWrapEngine();
    case Rijndael:
        return new RijndaelEngine();
    case Camellia:
        return new CamelliaEngine();
    case Blowfish:
        return new BlowfishEngine();
    case Serpent:
        return new SerpentEngine();
    case Threefish:
        // return new ThreefishEngine(256);
        return new ThreefishEngine(ThreefishSize);
    case Twofish:
    default:
        return new TwofishEngine();
    }
}

From source file:jcrypter.JCrypterFrame.java

License:Apache License

/**
 * Test if the unlimited strength policy files are installed
 *///  w ww . j a va2s. co m
private void testUnlimitedPolicy() {
    try {
        byte[] data = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

        // create a 64 bit secret key from raw bytes

        byte[] key = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; //NOI18N

        byte[] out = new byte[256];

        // create a cipher and attempt to encrypt the data block with our key

        BlockCipher c = new BlowfishEngine();

        c.init(true, new KeyParameter(key));
        c.processBlock(data, 0, out, 0);
        c.reset();

        // create a 192 bit secret key from raw bytes

        SecretKey key192 = new SecretKeySpec(new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 },
                "Blowfish"); //NOI18N

        // now try encrypting with the larger key

        c.init(true, new KeyParameter(out));
        c.processBlock(data, 0, out, 0);
        //If no exception is thrown before
        System.out.println(i18n.getString("Unrestricted_policy_test:_passed"));
    }
    /*catch (InvalidKeyException ex)
    {
    JOptionPane.showMessageDialog(this, i18n.getString("The_Unrestricted_Policy_Files_are_not_installed_in_your_JRE.") +
            i18n.getString("Please_install_them_to_enable_strong_cryptography!"), i18n.getString("Restricted_policy_files"),
            JOptionPane.ERROR_MESSAGE);
    }*/
    catch (Exception ex) {
        Logger.getLogger(JCrypterFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:net.sf.jsignpdf.JSignEncryptor.java

License:Mozilla Public License

/**
 * Initialize the cryptographic engine.//from  ww w  .j  av a 2s.  c o  m
 * 
 * @param aKey
 */
public JSignEncryptor(final byte[] aKey) {
    cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new BlowfishEngine()));
    key = new KeyParameter(aKey);
}

From source file:org.cryptacular.spec.BlockCipherSpec.java

License:Open Source License

@Override
public BlockCipher newInstance() {
    BlockCipher cipher;/*from  w  ww.  j  a v  a  2s.c om*/
    if ("AES".equalsIgnoreCase(algorithm)) {
        cipher = new AESFastEngine();
    } else if ("Blowfish".equalsIgnoreCase(algorithm)) {
        cipher = new BlowfishEngine();
    } else if ("Camellia".equalsIgnoreCase(algorithm)) {
        cipher = new CamelliaEngine();
    } else if ("CAST5".equalsIgnoreCase(algorithm)) {
        cipher = new CAST5Engine();
    } else if ("CAST6".equalsIgnoreCase(algorithm)) {
        cipher = new CAST6Engine();
    } else if ("DES".equalsIgnoreCase(algorithm)) {
        cipher = new DESEngine();
    } else if ("DESede".equalsIgnoreCase(algorithm) || "DES3".equalsIgnoreCase(algorithm)) {
        cipher = new DESedeEngine();
    } else if ("GOST".equalsIgnoreCase(algorithm) || "GOST28147".equals(algorithm)) {
        cipher = new GOST28147Engine();
    } else if ("Noekeon".equalsIgnoreCase(algorithm)) {
        cipher = new NoekeonEngine();
    } else if ("RC2".equalsIgnoreCase(algorithm)) {
        cipher = new RC2Engine();
    } else if ("RC5".equalsIgnoreCase(algorithm)) {
        cipher = new RC564Engine();
    } else if ("RC6".equalsIgnoreCase(algorithm)) {
        cipher = new RC6Engine();
    } else if ("SEED".equalsIgnoreCase(algorithm)) {
        cipher = new SEEDEngine();
    } else if ("Serpent".equalsIgnoreCase(algorithm)) {
        cipher = new SerpentEngine();
    } else if ("Skipjack".equalsIgnoreCase(algorithm)) {
        cipher = new SkipjackEngine();
    } else if ("TEA".equalsIgnoreCase(algorithm)) {
        cipher = new TEAEngine();
    } else if ("Twofish".equalsIgnoreCase(algorithm)) {
        cipher = new TwofishEngine();
    } else if ("XTEA".equalsIgnoreCase(algorithm)) {
        cipher = new XTEAEngine();
    } else {
        throw new IllegalStateException("Unsupported cipher algorithm " + algorithm);
    }
    return cipher;
}

From source file:org.cryptacular.util.CipherUtilTest.java

License:Open Source License

@DataProvider(name = "block-cipher")
public Object[][] getBlockCipherData() {
    return new Object[][] { new Object[] {
            // Plaintext is NOT multiple of block size
            "Able was I ere I saw elba.", new CBCBlockCipher(new AESEngine()), new RBGNonce(16), },
            // Plaintext is multiple of block size
            new Object[] { "Four score and seven years ago, our forefathers ",
                    new CBCBlockCipher(new BlowfishEngine()), new RBGNonce(8), },
            // OFB
            new Object[] { "Have you passed through this night?", new OFBBlockCipher(new BlowfishEngine(), 64),
                    new LongCounterNonce(), },
            // CFB
            new Object[] {
                    "I went to the woods because I wished to live deliberately, to "
                            + "front only the essential facts of life",
                    new CFBBlockCipher(new AESEngine(), 128), new RBGNonce(16), }, };
}