org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher Java Examples

The following examples show how to use org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SecurityHandler.java    From sambox with Apache License 2.0 7 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))
    {
        IOUtils.copy(cis, output);
    }
}
 
Example #2
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesDecrypt(byte[] encrypted, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        if (encrypted.length < 16 || encrypted.length % 16 != 0) {
            throw new InvalidCipherTextException("invalid ciphertext");
        }
        byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
        byte[] ciphertext = Arrays.copyOfRange(encrypted, 16, encrypted.length);
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        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 #3
Source File: DESEncrypter.java    From gocd with Apache License 2.0 6 votes vote down vote up
private static String decrypt(byte[] key, String cipherText) throws CryptoException {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
        cipher.init(false, new KeyParameter(key));
        byte[] cipherTextBytes = DECODER.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);
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}
 
Example #4
Source File: AESCBC.java    From InflatableDonkey with MIT License 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 #5
Source File: BCStrongAESEncryption.java    From Hive2Hive with MIT License 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 #6
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 6 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 #7
Source File: UploadEncryptFileController.java    From Spring-MVC-Blueprints with MIT License 6 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 #8
Source File: CmsCryptoDES.java    From oneops with Apache License 2.0 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 #9
Source File: CmsCryptoDES.java    From oneops with Apache License 2.0 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 #10
Source File: BurstCryptoImpl.java    From burstkit4j with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] aesEncrypt(byte[] plaintext, byte[] signingKey, byte[] nonce) {
    if (signingKey.length != 32) {
        throw new IllegalArgumentException("Key length must be 32 bytes");
    }
    try {
        for (int i = 0; i < 32; i++) {
            signingKey[i] ^= nonce[i];
        }
        byte[] key = getSha256().digest(signingKey);
        byte[] iv = new byte[16];
        secureRandom.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 #11
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter解密
 *
 * @param dataToDecrypt 需要解密的数据
 * @param aesKey        秘钥
 * @return 解密后的数据
 */
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    HexUtil.checkNotNull(dataToDecrypt);
    HexUtil.checkNotNull(aesKey);

    try {
        ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), dataToDecrypt.getInitialisationVector());

        // Decrypt the validator.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, keyWithIv);

        byte[] cipherBytes = dataToDecrypt.getEncryptedBytes();
        byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];
        final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);
        final int length2 = cipher.doFinal(decryptedBytes, length1);

        return Arrays.copyOf(decryptedBytes, length1 + length2);
    } catch (Exception e) {
        throw new CryptoException();
    }
}
 
Example #12
Source File: AESEncrypt.java    From nuls-v2 with MIT License 6 votes vote down vote up
/**
 * 数据通过KeyParameter和初始化向量加密
 *
 * @param plainBytes 需要加密的数据
 * @param iv         初始化向量
 * @param aesKey     秘钥
 * @return 加密后的数据
 */
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    HexUtil.checkNotNull(plainBytes);
    HexUtil.checkNotNull(aesKey);
    try {
        if (iv == null) {
            iv = EncryptedData.DEFAULT_IV;
            //SECURE_RANDOM.nextBytes(iv);
        }
        ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);
        // Encrypt using AES.
        BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, keyWithIv);
        byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];
        final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);
        final int length2 = cipher.doFinal(encryptedBytes, length1);

        return new EncryptedData(iv, Arrays.copyOf(encryptedBytes, length1 + length2));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #13
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data)
        throws IllegalStateException, InvalidCipherTextException {
    int minSize = cipher.getOutputSize(data.length);
    byte[] outBuf = new byte[minSize];
    int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0);
    int length2 = cipher.doFinal(outBuf, length1);
    int actualLength = length1 + length2;
    if (actualLength == minSize) {
        return outBuf;
    } else {
        return Arrays.copyOf(outBuf, actualLength);
    }
}
 
Example #14
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] encrypt(byte[] data, byte[] randomKeyBytes) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(true, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #15
Source File: DESEncrypter.java    From gocd with Apache License 2.0 5 votes vote down vote up
private static String encrypt(byte[] key, String plainText) throws CryptoException {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
        KeyParameter keyParameter = new KeyParameter(key);
        cipher.init(true, keyParameter);
        byte[] plainTextBytes = plainText.getBytes();
        byte[] cipherTextBytes = new byte[cipher.getOutputSize(plainTextBytes.length)];
        int outputLength = cipher.processBytes(plainTextBytes, 0, plainTextBytes.length, cipherTextBytes, 0);
        cipher.doFinal(cipherTextBytes, outputLength);
        return ENCODER.encodeToString(cipherTextBytes).trim();
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}
 
Example #16
Source File: AESEncryptor.java    From archistar-smc with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] decrypt(byte[] data, byte[] randomKeyBytes)
        throws InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalStateException, InvalidCipherTextException {

    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    cipher.init(false, new ParametersWithIV(new KeyParameter(randomKeyBytes), randomIvBytes));
    return cipherData(cipher, data);
}
 
Example #17
Source File: GeoWaveEncryption.java    From geowave with Apache License 2.0 5 votes vote down vote up
private PaddedBufferedBlockCipher getCipher(final boolean encrypt) {
  final PaddedBufferedBlockCipher cipher =
      new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), new PKCS7Padding());
  final CipherParameters ivAndKey =
      new ParametersWithIV(new KeyParameter(getKey().getEncoded()), salt);
  cipher.init(encrypt, ivAndKey);
  return cipher;
}
 
Example #18
Source File: Encryptor.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
public Encryptor(String encryptKey) {
  encryptCipher = new PaddedBufferedBlockCipher(new AESEngine(), new ZeroBytePadding());
  encryptCipher.init(true, new KeyParameter(encryptKey.getBytes()));

  decryptCipher = new PaddedBufferedBlockCipher(new AESEngine(), new ZeroBytePadding());
  decryptCipher.init(false, new KeyParameter(encryptKey.getBytes()));
}
 
Example #19
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
public String testDecryptRijndael(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(false, new KeyParameter(keyBytes));

        byte[] output = Base64.decode(value.getBytes());
        byte[] cipherText = new byte[cipher.getOutputSize(output.length)];

        int cipherLength = cipher.processBytes(output, 0, output.length, cipherText, 0);
        int outputLength = cipher.doFinal(cipherText, cipherLength);
        outputLength += cipherLength;

        byte[] resultBytes = cipherText;
        if (outputLength != output.length) {
            resultBytes = new byte[outputLength];
            System.arraycopy(
                    cipherText, 0,
                    resultBytes, 0,
                    outputLength
            );
        }

        String result = new String(resultBytes);
return  result;
    }
 
Example #20
Source File: DownloadDecryptFileController.java    From Spring-MVC-Blueprints with MIT License 5 votes vote down vote up
public byte[] decryptDESFile(String key, byte[] cipherText) {
BlockCipher engine = new DESEngine();
      byte[] bytes = key.getBytes();
      BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(engine));
      cipher.init(false, new KeyParameter(bytes));
      byte[] rv = new byte[cipher.getOutputSize(cipherText.length)];
      int tam = cipher.processBytes(cipherText, 0, cipherText.length, rv, 0);
      try {
          cipher.doFinal(rv, tam);
      } catch (Exception ce) {
          ce.printStackTrace();
      }
      return rv;
  }
 
Example #21
Source File: AESCipher.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** Creates a new instance of AESCipher */
public AESCipher(boolean forEncryption, byte[] key, byte[] iv) {
    BlockCipher aes = new AESFastEngine();
    BlockCipher cbc = new CBCBlockCipher(aes);
    bp = new PaddedBufferedBlockCipher(cbc);
    KeyParameter kp = new KeyParameter(key);
    ParametersWithIV piv = new ParametersWithIV(kp, iv);
    bp.init(forEncryption, piv);
}
 
Example #22
Source File: Ed25519BlockCipher.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
public static BufferedBlockCipher setupBlockCipher(
    final byte[] sharedKey, final byte[] ivData, final boolean forEncryption) {
    // Setup cipher parameters with key and IV.
    final KeyParameter keyParam = new KeyParameter(sharedKey);
    final CipherParameters params = new ParametersWithIV(keyParam, ivData);

    // Setup AES cipher in CBC mode with PKCS7 padding.
    final BlockCipherPadding padding = new PKCS7Padding();
    final BufferedBlockCipher cipher =
        new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESEngine()), padding);
    cipher.reset();
    cipher.init(forEncryption, params);
    return cipher;
}
 
Example #23
Source File: CrmfKeyWrapper.java    From xipki with Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the key with the following output.
 * <pre>
 * ECIES-Ciphertext-Value ::= SEQUENCE {
 *     ephemeralPublicKey ECPoint,
 *     symmetricCiphertext OCTET STRING,
 *     macTag OCTET STRING
 * }
 *
 * ECPoint ::= OCTET STRING
 * </pre>
 */
@Override
public byte[] generateWrappedKey(byte[] keyToWrap) throws OperatorException {
  try {
    BlockCipher cbcCipher = new CBCBlockCipher(new AESEngine());
    IESCipher cipher = new IESCipher(
        new IESEngine(new ECDHBasicAgreement(),
            new KDF2BytesGenerator(new SHA1Digest()),
            new HMac(new SHA1Digest()),
            new PaddedBufferedBlockCipher(cbcCipher)), 16);

    // According to the §3.8 in SEC 1, Version 2.0:
    // "Furthermore here the 16 octet or 128 bit IV for AES in CBC mode should always take
    //  the value 0000000000000000_{16}"
    byte[] iv = new byte[16];
    IESParameterSpec spec = new IESParameterSpec(null, null, aesKeySize, aesKeySize, iv);
    cipher.engineInit(Cipher.ENCRYPT_MODE, publicKey, spec, new SecureRandom());
    byte[] bcResult = cipher.engineDoFinal(keyToWrap, 0, keyToWrap.length);
    // convert the result to ASN.1 format
    ASN1Encodable[] array = new ASN1Encodable[3];
    // ephemeralPublicKey ECPoint
    byte[] ephemeralPublicKey = new byte[ephemeralPublicKeyLen];

    System.arraycopy(bcResult, 0, ephemeralPublicKey, 0, ephemeralPublicKeyLen);
    array[0] = new DEROctetString(ephemeralPublicKey);

    // symmetricCiphertext OCTET STRING
    int symmetricCiphertextLen = bcResult.length - ephemeralPublicKeyLen - macLen;
    byte[] symmetricCiphertext = new byte[symmetricCiphertextLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen,
        symmetricCiphertext, 0, symmetricCiphertextLen);
    array[1] = new DEROctetString(symmetricCiphertext);

    // macTag OCTET STRING
    byte[] macTag = new byte[macLen];
    System.arraycopy(bcResult, ephemeralPublicKeyLen + symmetricCiphertextLen,
        macTag, 0, macLen);
    array[2] = new DEROctetString(macTag);
    return new DERSequence(array).getEncoded();
  } catch (Exception ex) {
    throw new OperatorException("error while generateWrappedKey", ex);
  }
}
 
Example #24
Source File: ConcatenatingAESEngine.java    From sambox with Apache License 2.0 4 votes vote down vote up
ConcatenatingAESEngine()
{
    super(new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine())));
    random = new SecureRandom();
}