Java Code Examples for org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher

The following are top voted examples for showing how to use org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lastpass-java   File: SimpleAesManaged.java   View source code 8 votes vote down vote up
@Override
    public String decrypt(byte[] encrypted) {
//        Cipher cipher = null;
        String plain;
        try {
//            Security.addProvider(new BouncyCastlePQCProvider());
//            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", new BouncyCastlePQCProvider());
//            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new IvParameterSpec(iv));
//            plain = new String(cipher.doFinal(encrypted), "UTF-8");
            KeyParameter keyParam = new KeyParameter(encryptionKey);
            CipherParameters params = new ParametersWithIV(keyParam, iv);
            BlockCipherPadding padding = new PKCS7Padding();
            BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                    new CBCBlockCipher(new AESEngine()), padding);
            cipher.reset();
            cipher.init(false, params);
            byte[] buffer = new byte[cipher.getOutputSize(encrypted.length)];
            int len = cipher.processBytes(encrypted, 0, encrypted.length, buffer, 0);
            len += cipher.doFinal(buffer, len);
            byte[] out = Arrays.copyOfRange(buffer, 0, len);
            plain = new String(out, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("decrypt error in SimpleAesManaged", e);
        }
        return plain;
    }
 
Example 2
Project: lastpass-java   File: ParserHelperTest.java   View source code 8 votes vote down vote up
private static byte[] EncryptAes256(byte[] data, byte[] encryptionKey)
{
    try {
        KeyParameter keyParam = new KeyParameter(encryptionKey);
        BlockCipherPadding padding = new PKCS7Padding();
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), padding);
        cipher.reset();
        cipher.init(true, keyParam);
        byte[] buffer = new byte[cipher.getOutputSize(data.length)];
        int len = cipher.processBytes(data, 0, data.length, buffer, 0);
        len += cipher.doFinal(buffer, len);
        return Arrays.copyOfRange(buffer, 0, len);
    } catch (Exception e) {
        throw new RuntimeException("decrypt error in SimpleAesManaged", e);
    }
}
 
Example 3
Project: ExamplesAndroid   File: Metodos.java   View source code 8 votes vote down vote up
public String testEncryptRijndael(String value,String key) throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    BlockCipher engine = new RijndaelEngine(256);
    BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine), new ZeroBytePadding());

    byte[] keyBytes = key.getBytes();
    cipher.init(true, new KeyParameter(keyBytes));

    byte[] input = value.getBytes();
    byte[] cipherText = new byte[cipher.getOutputSize(input.length)];

    int cipherLength = cipher.processBytes(input, 0, input.length, cipherText, 0);
    cipher.doFinal(cipherText, cipherLength);

    String result = new String(Base64.encode(cipherText));
    //Log.e("testEncryptRijndael : " , result);
    return  result;
}
 
Example 4
Project: Spring-MVC-Blueprints   File: UploadEncryptFileController.java   View source code 7 votes vote down vote up
private byte[] encryptDESFile(String keys, byte[] plainText) {
BlockCipher engine = new DESEngine();

      byte[] key = keys.getBytes();
      byte[] ptBytes = plainText;
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(true, new KeyParameter(key));
      byte[] rv = new byte[cipher.getOutputSize(ptBytes.length)];
      int tam = cipher.processBytes(ptBytes, 0, ptBytes.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example 5
Project: burstcoin   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 6
Project: oneops   File: CmsCryptoDES.java   View source code 6 votes vote down vote up
/**
 * Encrypt.
 *
 * @param instr the instr
 * @return the string
 * @throws java.security.GeneralSecurityException the general security exception
 */
@Override
public String encrypt(String instr) throws GeneralSecurityException {
    long t1 = System.currentTimeMillis();
    byte[] in = instr.getBytes();
    PaddedBufferedBlockCipher encryptor = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new DESedeEngine()));
    encryptor.init(true, keyParameter);
    byte[] cipherText = new byte[encryptor.getOutputSize(in.length)];
    int outputLen = encryptor.processBytes(in, 0, in.length, cipherText, 0);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        encryptor.doFinal(cipherText, outputLen);
        Hex.encode(cipherText, os);
    } catch (Exception e) {
        e.printStackTrace();
        throw new GeneralSecurityException(e);
    }
    long t2 = System.currentTimeMillis();
    logger.debug("Time taken to encrypt(millis) :" + (t2 - t1));
    return ENC_PREFIX + os.toString();
}
 
Example 7
Project: oneops   File: CmsCryptoDES.java   View source code 6 votes vote down vote up
private String decryptStr(String instr) throws GeneralSecurityException {
    if(StringUtils.isEmpty(instr)){
        return instr;
    }
    long t1 = System.currentTimeMillis();
    PaddedBufferedBlockCipher decryptor = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new DESedeEngine()));
    decryptor.init(false, keyParameter);
    byte[] in = null;
    byte[] cipherText = null;

    try {
    	in = Hex.decode(instr);
    	cipherText = new byte[decryptor.getOutputSize(in.length)];

     int outputLen = decryptor.processBytes(in, 0, in.length, cipherText, 0);
        decryptor.doFinal(cipherText, outputLen);
    } catch (Exception e) {
        throw new GeneralSecurityException(e);
    }
    long t2 = System.currentTimeMillis();
    logger.debug("Time taken to decrypt(millis) : " + (t2 - t1));
    return (new String(cipherText)).replaceAll("\\u0000+$", "");
}
 
Example 8
Project: burstcoin-faucet   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 9
Project: burstcoin-faucet   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte theirPublicKey[]) {
    try {
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        byte[] key = sha256().digest(dhSharedSecret);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 10
Project: gwt-crypto   File: SerpentTest.java   View source code 6 votes vote down vote up
private void doCbc(byte[] key, byte[] iv, byte[] pt, byte[] expected)
    throws Exception
{
    PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CBCBlockCipher(new SerpentEngine()), new PKCS7Padding());

    byte[] ct = new byte[expected.length];

    c.init(true, new ParametersWithIV(new KeyParameter(key), iv));

    int l = c.processBytes(pt, 0, pt.length, ct, 0);

    c.doFinal(ct, l);

    if (!Arrays.areEqual(expected, ct))
    {
        fail("CBC test failed");
    }
}
 
Example 11
Project: SecurityAndroid   File: BouncyCastleAPI_AES_CBC.java   View source code 6 votes vote down vote up
public void InitCiphers() {
	// create the ciphers
	// AES block cipher in CBC mode with padding
	encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
			new AESEngine()));

	decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
			new AESEngine()));

	// create the IV parameter
	ParametersWithIV parameterIV = new ParametersWithIV(new KeyParameter(
			key), IV);

	encryptCipher.init(true, parameterIV);
	decryptCipher.init(false, parameterIV);
}
 
Example 12
Project: java-security   File: PasswordBasedEncryption.java   View source code 6 votes vote down vote up
/**
 * A password-based data decryption using a constant salt value "<b>constantSalt</b>"
 * @param cipher
 * @param password
 * @param salt
 * @param iterationCount
 * @return
 * @throws Exception
 */
public static byte[] decrypt(byte[] cipher, String password) throws Exception
{
    PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(new SHA256Digest());
    char[] passwordChars = password.toCharArray();
    final byte[] pkcs12PasswordBytes = PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
    pGen.init(pkcs12PasswordBytes, constantSalt.getBytes(), iterations);
    CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
    ParametersWithIV aesCBCParams = (ParametersWithIV) pGen.generateDerivedParameters(256, 128);
    aesCBC.init(false, aesCBCParams);
    PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());
    byte[] plainTemp = new byte[aesCipher.getOutputSize(cipher.length)];
    int offset = aesCipher.processBytes(cipher, 0, cipher.length, plainTemp, 0);
    int last = aesCipher.doFinal(plainTemp, offset);
    final byte[] plain = new byte[offset + last];
    System.arraycopy(plainTemp, 0, plain, 0, plain.length);
    return plain;
}
 
Example 13
Project: bunkr   File: SimpleBlockCipher.java   View source code 6 votes vote down vote up
private static byte[] operate(Encryption encryptionAlgorithm, boolean doEncrypt, byte[] subject, byte[] key, byte[] iv) throws CryptoException
{
    // set up padded buffered cipher
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            CipherBuilder.buildCipher(encryptionAlgorithm, doEncrypt, key, iv), new PKCS7Padding()
    );

    // init with key and if
    cipher.init(doEncrypt, new ParametersWithIV(new KeyParameter(key), iv));

    // construct output buffer
    byte[] output = new byte[cipher.getOutputSize(subject.length)];

    // process all da bytes
    int cursor = cipher.processBytes(subject, 0, subject.length, output, 0);

    // process the last bytes from the buffer
    cipher.doFinal(output, cursor);
    return output;
}
 
Example 14
Project: risecoin   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 15
Project: burstcoin-jminer   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 16
Project: burstcoin-jminer   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte theirPublicKey[]) {
    try {
        if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length);
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        byte[] key = sha256().digest(dhSharedSecret);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(false, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(ciphertext.length)];
        int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0);
        plaintextLength += aes.doFinal(output, plaintextLength);
        byte[] result = new byte[plaintextLength];
        System.arraycopy(output, 0, result, 0, result.length);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 17
Project: animamea   File: AmAESCrypto.java   View source code 6 votes vote down vote up
private void initCiphers(byte[] key, byte[] iv) {

		// get the keyBytes
		keyBytes = new byte[key.length];
		System.arraycopy(key, 0, keyBytes, 0, key.length);

		keyP = new KeyParameter(keyBytes);

		// get the IV
		IV = new byte[blockSize];
		System.arraycopy(iv, 0, IV, 0, IV.length);

		// create the ciphers
		// AES block cipher in CBC mode with ISO7816d4 padding
		encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
				new AESFastEngine()), new ISO7816d4Padding());

		decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
				new AESFastEngine()), new ISO7816d4Padding());

		// create the IV parameter
		ParametersWithIV parameterIV = new ParametersWithIV(keyP, IV);

		encryptCipher.init(true, parameterIV);
		decryptCipher.init(false, parameterIV);
	}
 
Example 18
Project: animamea   File: AmDESCrypto.java   View source code 6 votes vote down vote up
private void initCiphers(byte[] key, byte[] iv) {
	// get the keyBytes
	keyBytes = new byte[key.length];
	System.arraycopy(key, 0, keyBytes, 0, key.length);

	// get the IV
	IV = new byte[blockSize];
	System.arraycopy(iv, 0, IV, 0, iv.length);

	keyP = new KeyParameter(keyBytes);

	encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
			new DESedeEngine()), new ISO7816d4Padding());
	decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(
			new DESedeEngine()), new ISO7816d4Padding());

	// create the IV parameter
	ParametersWithIV parameterIV = new ParametersWithIV(keyP, IV);

	encryptCipher.init(true, parameterIV);
	decryptCipher.init(false, parameterIV);
}
 
Example 19
Project: PasswordSafe   File: DataFormatV1.java   View source code 6 votes vote down vote up
private static final byte[] encrypt(byte[] key, byte[] data) throws Exception
{
	PaddedBufferedBlockCipher c = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()));
	CipherParameters p = new KeyParameter(key);
	try
	{
		SecretByteArrayOutputStream ba = new SecretByteArrayOutputStream();
		try
		{
			XCipherOutputStream out = new XCipherOutputStream(c, p, ba);
			out.write(data);
			out.close();
	
			byte[] b = ba.toByteArray();
			return b;
		}
		finally
		{
			CKit.close(ba);
		}
	}
	finally
	{
		Crypto.zero(p);
	}
}
 
Example 20
Project: horizon-blocknet   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 21
Project: jCryptTool   File: AesEncryptionService.java   View source code 6 votes vote down vote up
@Override
public OutputStream encryptedOutputStream(final Path path, final String password) throws IOException,
        EncryptionFailedException {
    try {
        final byte[] salt = generateSalt();
        final byte[] key = generateKey(password, salt);
        final byte[] iv = generateIV();
        final byte[] fileInitBlock = generateOutputInitBlock(salt, iv);

        final PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
                new CBCBlockCipher(new AESEngine()), new PKCS7Padding());

        final KeyParameter keyParam = new KeyParameter(key);
        final CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(true, params);

        final BufferedOutputStream out = new BufferedOutputStream(Files.newOutputStream(path));
        out.write(fileInitBlock);

        return new CipherOutputStream(out, cipher);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new EncryptionFailedException(e);
    }
}
 
Example 22
Project: jCryptTool   File: AesEncryptionService.java   View source code 6 votes vote down vote up
@Override
public InputStream decryptedInputStream(final Path path, final String password) throws IOException,
        DecryptionFailedException {
    try {
        InputStream in = new BufferedInputStream(Files.newInputStream(path));
        byte[] initBlock = readInitBlock(in);
        byte[] salt = extractSalt(initBlock);
        byte[] iv = extractIV(initBlock);
        byte[] key = generateKey(password, salt);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()),
                new PKCS7Padding());
        KeyParameter keyParam = new KeyParameter(key);
        CipherParameters params = new ParametersWithIV(keyParam, iv);
        cipher.init(false, params);

        return new CipherInputStream(in, cipher);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new DecryptionFailedException(e);
    }
}
 
Example 23
Project: keepassj   File: StandardAesEngine.java   View source code 6 votes vote down vote up
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 {
//                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);
            }
		}
 
Example 24
Project: keepassj   File: StandardAesEngine.java   View source code 6 votes vote down vote up
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 {
                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);
            }
        }
 
Example 25
Project: blockchain   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 26
Project: InflatableDonkey   File: AESCBC.java   View source code 6 votes vote down vote up
public static byte[] decryptAESCBC(byte[] key, byte[] iv, byte[] data) {
    // AES CBC PKCS7 decrypt
    try {
        CipherParameters cipherParameters = new ParametersWithIV(new KeyParameter(key), iv);
        PaddedBufferedBlockCipher cipher
                = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()), new PKCS7Padding());
        cipher.init(false, cipherParameters);

        byte[] buffer = new byte[cipher.getOutputSize(data.length)];

        int pos = cipher.processBytes(data, 0, data.length, buffer, 0);
        pos += cipher.doFinal(buffer, pos);

        return Arrays.copyOf(buffer, pos);

    } catch (DataLengthException | IllegalStateException | InvalidCipherTextException ex) {
        throw new IllegalArgumentException("decrypt failed", ex);
    }
}
 
Example 27
Project: ezbake-common-java   File: TDESCryptoTest.java   View source code 6 votes vote down vote up
@Test
public void test() throws DataLengthException, IllegalStateException, InvalidCipherTextException {
    PaddedBufferedBlockCipher encryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
    PaddedBufferedBlockCipher decryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
    
    byte inBuff[] = "Hello Wd".getBytes();
    byte[] outBuff = new byte[512];
    byte[] keyBytes = "TestTestTestTest".getBytes();
    byte[] uncipherData = new byte[8];
    
    encryptCipher.init(true, new KeyParameter(keyBytes));
    decryptCipher.init(false, new KeyParameter(keyBytes));
    
    encryptCipher.processBytes(inBuff, 0, inBuff.length, outBuff, 0);
    encryptCipher.doFinal(outBuff, 0);
    
    decryptCipher.processBytes(outBuff, 0, 2*inBuff.length, uncipherData, 0);
    decryptCipher.doFinal(uncipherData, 0);
    
    log.debug("Uncipher Data: {}", uncipherData);
    
    assertTrue("Hello Wd".equals(new String(uncipherData)));
}
 
Example 28
Project: sambox   File: SecurityHandler.java   View source code 6 votes vote down vote up
/**
 * Encrypt or decrypt data with AES256.
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAES256(InputStream data, OutputStream output) throws IOException
{
    byte[] iv = new byte[16];

    // read IV from stream
    int ivSize = data.read(iv);
    if (ivSize == -1)
    {
        return;
    }

    if (ivSize != iv.length)
    {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
            new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(encryptionKey), iv));
    try (CipherInputStream cis = new CipherInputStream(data, cipher))
    {
        org.apache.commons.io.IOUtils.copy(cis, output);
    }
}
 
Example 29
Project: ROKOS-OK-Bitcoin-Fullnode   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 30
Project: nxt   File: Crypto.java   View source code 6 votes vote down vote up
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) {
    try {
        byte[] dhSharedSecret = new byte[32];
        Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey);
        for (int i = 0; i < 32; i++) {
            dhSharedSecret[i] ^= nonce[i];
        }
        byte[] key = sha256().digest(dhSharedSecret);
        byte[] iv = new byte[16];
        secureRandom.get().nextBytes(iv);
        PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
                new AESEngine()));
        CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
        aes.init(true, ivAndKey);
        byte[] output = new byte[aes.getOutputSize(plaintext.length)];
        int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0);
        ciphertextLength += aes.doFinal(output, ciphertextLength);
        byte[] result = new byte[iv.length + ciphertextLength];
        System.arraycopy(iv, 0, result, 0, iv.length);
        System.arraycopy(output, 0, result, iv.length, ciphertextLength);
        return result;
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}
 
Example 31
Project: BitcoinCore   File: EncryptedPrivateKey.java   View source code 6 votes vote down vote up
/**
 * Returns the decrypted private key
 *
 * @param       keyPhrase       Key phrase used to derive the encryption key
 * @return                      Private key
 * @throws      ECException     Unable to complete a cryptographic function
 */
public BigInteger getPrivKey(String keyPhrase) throws ECException {
    KeyParameter aesKey = deriveKey(keyPhrase, salt);
    //
    // Decrypt the private key using the generated AES key
    //
    BigInteger privKey;
    try {
        ParametersWithIV keyWithIV = new ParametersWithIV(aesKey, iv);
        CBCBlockCipher blockCipher = new CBCBlockCipher(new AESEngine());
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher);
        cipher.init(false, keyWithIV);
        int bufferLength = cipher.getOutputSize(encKeyBytes.length);
        byte[] outputBytes = new byte[bufferLength];
        int length1 = cipher.processBytes(encKeyBytes, 0, encKeyBytes.length, outputBytes, 0);
        int length2 = cipher.doFinal(outputBytes, length1);
        int actualLength = length1 + length2;
        byte[] privKeyBytes = new byte[actualLength];
        System.arraycopy(outputBytes, 0, privKeyBytes, 0, actualLength);
        privKey = new BigInteger(privKeyBytes);
    } catch (Exception exc) {
        throw new ECException("Unable to decrypt the private key", exc);
    }
    return privKey;
}
 
Example 32
Project: sblit   File: SymmetricEncryption.java   View source code 6 votes vote down vote up
private byte[] process(byte[] data, boolean encryption) throws DataLengthException {
	BlockCipher cipher = new AESEngine();
	BlockCipherPadding padding = new ZeroBytePadding();
	BufferedBlockCipher bufferedCipher = new PaddedBufferedBlockCipher(cipher, padding);
	bufferedCipher.init(encryption, key);
	byte[] output = new byte[bufferedCipher.getOutputSize(data.length)];
	int bytesProcessed = bufferedCipher.processBytes(data, 0, data.length, output, 0);
	try {
		bufferedCipher.doFinal(output, bytesProcessed);
		return output;
	} catch (IllegalStateException
			| InvalidCipherTextException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 33
Project: gocd   File: GoCipher.java   View source code 6 votes vote down vote up
public String decipher(byte[] key, String cipherText) throws InvalidCipherTextException {
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
    cipher.init(false, new KeyParameter(Hex.decode(key)));
    byte[] cipherTextBytes = java.util.Base64.getDecoder().decode(cipherText);

    byte[] plainTextBytes = new byte[cipher.getOutputSize(cipherTextBytes.length)];
    int outputLength = cipher.processBytes(cipherTextBytes, 0, cipherTextBytes.length, plainTextBytes, 0);
    cipher.doFinal(plainTextBytes, outputLength);
    int paddingStarts = plainTextBytes.length - 1;
    for (; paddingStarts >= 0 ; paddingStarts--) {
        if (plainTextBytes[paddingStarts] != 0) {
            break;
        }
    }
    return new String(plainTextBytes, 0, paddingStarts + 1);
}
 
Example 34
Project: Hive2Hive   File: BCStrongAESEncryption.java   View source code 6 votes vote down vote up
private static byte[] processAESCipher(boolean encrypt, byte[] data, SecretKey key, byte[] initVector)
		throws DataLengthException, IllegalStateException, InvalidCipherTextException {
	// seat up engine, block cipher mode and padding
	AESEngine aesEngine = new AESEngine();
	CBCBlockCipher cbc = new CBCBlockCipher(aesEngine);
	PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc);

	// apply parameters
	CipherParameters parameters = new ParametersWithIV(new KeyParameter(key.getEncoded()), initVector);
	cipher.init(encrypt, parameters);

	// process ciphering
	byte[] output = new byte[cipher.getOutputSize(data.length)];

	int bytesProcessed1 = cipher.processBytes(data, 0, data.length, output, 0);
	int bytesProcessed2 = cipher.doFinal(output, bytesProcessed1);
	byte[] result = new byte[bytesProcessed1 + bytesProcessed2];
	System.arraycopy(output, 0, result, 0, result.length);
	return result;
}
 
Example 35
Project: kloudmake   File: AESHelper.java   View source code 6 votes vote down vote up
private static byte[] crypt(final boolean encrypt, final byte[] bytes, final String password, final byte[] salt) throws InvalidCipherTextException {
    final PBEParametersGenerator keyGenerator = new PKCS12ParametersGenerator(new SHA256Digest());
    keyGenerator.init(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password.toCharArray()), salt, 20);
    final CipherParameters keyParams = keyGenerator.generateDerivedParameters(256, 128);

    final BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
    cipher.init(encrypt, keyParams);

    final byte[] processed = new byte[cipher.getOutputSize(bytes.length)];
    int outputLength = cipher.processBytes(bytes, 0, bytes.length, processed, 0);
    outputLength += cipher.doFinal(processed, outputLength);

    final byte[] results = new byte[outputLength];
    System.arraycopy(processed, 0, results, 0, outputLength);
    return results;
}
 
Example 36
Project: MyDMAM   File: Password.java   View source code 6 votes vote down vote up
/**
 * @return AES(BCrypt(clear_password, 10), SHA256(master_password_key))
 */
public byte[] getHashedPassword(String clear_password) throws SecurityException {
	String tested_password = testIfPasswordIsStrong(clear_password);
	try {
		byte[] hashed = (BCrypt.hashpw(tested_password, BCrypt.gensalt(10))).getBytes("UTF-8");
		
		BlockCipherPadding padding = new PKCS7Padding();
		BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
		cipher.reset();
		cipher.init(true, params);
		
		byte[] buf = new byte[cipher.getOutputSize(hashed.length)];
		int len = cipher.processBytes(hashed, 0, hashed.length, buf, 0);
		len += cipher.doFinal(buf, len);
		
		byte[] out = new byte[len];
		System.arraycopy(buf, 0, out, 0, len);
		
		return out;
	} catch (Exception e) {
		Loggers.Auth.error("Can't prepare password", e);
	}
	return null;
}
 
Example 37
Project: MyDMAM   File: Password.java   View source code 6 votes vote down vote up
public boolean checkPassword(String candidate_password, byte[] raw_password) {
	try {
		BlockCipherPadding padding = new PKCS7Padding();
		BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
		cipher.reset();
		cipher.init(false, params);
		
		byte[] buf = new byte[cipher.getOutputSize(raw_password.length)];
		int len = cipher.processBytes(raw_password, 0, raw_password.length, buf, 0);
		len += cipher.doFinal(buf, len);
		
		return BCrypt.checkpw(candidate_password, new String(buf, 0, len));
	} catch (Exception e) {
		Loggers.Auth.error("Can't extract hashed password", e);
	}
	return false;
}
 
Example 38
Project: ipack   File: BrokenJCEBlockCipher.java   View source code 5 votes vote down vote up
protected BrokenJCEBlockCipher(
    BlockCipher engine,
    int         pbeType,
    int         pbeHash,
    int         pbeKeySize,
    int         pbeIvSize)
{
    cipher = new PaddedBufferedBlockCipher(engine);

    this.pbeType = pbeType;
    this.pbeHash = pbeHash;
    this.pbeKeySize = pbeKeySize;
    this.pbeIvSize = pbeIvSize;
}
 
Example 39
Project: ipack   File: BcPKCS12PBEInputDecryptorProviderBuilder.java   View source code 5 votes vote down vote up
public InputDecryptorProvider build(final char[] password)
{
    return new InputDecryptorProvider()
    {
        public InputDecryptor get(final AlgorithmIdentifier algorithmIdentifier)
        {
            final PaddedBufferedBlockCipher engine = PKCS12PBEUtils.getEngine(algorithmIdentifier.getAlgorithm());

            PKCS12PBEParams           pbeParams = PKCS12PBEParams.getInstance(algorithmIdentifier.getParameters());

            CipherParameters params = PKCS12PBEUtils.createCipherParameters(algorithmIdentifier.getAlgorithm(), digest, engine.getBlockSize(), pbeParams, password);

            engine.init(false, params);

            return new InputDecryptor()
            {
                public AlgorithmIdentifier getAlgorithmIdentifier()
                {
                    return algorithmIdentifier;
                }

                public InputStream getInputStream(InputStream input)
                {
                    return new CipherInputStream(input, engine);
                }

                public GenericKey getKey()
                {
                    return new GenericKey(PKCS12ParametersGenerator.PKCS12PasswordToBytes(password));
                }
            };
        }
    };

}
 
Example 40
Project: ipack   File: DESExample.java   View source code 5 votes vote down vote up
private void process()
{
    /* 
     * Setup the DESede cipher engine, create a PaddedBufferedBlockCipher
     * in CBC mode.
     */
    cipher = new PaddedBufferedBlockCipher(
                                new CBCBlockCipher(new DESedeEngine()));

    /*
     * The input and output streams are currently set up
     * appropriately, and the key bytes are ready to be
     * used.
     *
     */

    if (encrypt)
    {
        performEncrypt(key);
    }
    else
    {
        performDecrypt(key);
    }

    // after processing clean up the files
    try
    {
        in.close();
        out.flush();
        out.close();
    }
    catch (IOException closing)
    {

    }
}