org.spongycastle.crypto.params.ParametersWithIV Java Examples

The following examples show how to use org.spongycastle.crypto.params.ParametersWithIV. 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: KeyCrypterScrypt.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt The data to decrypt
 * @param aesKey        The AES key to use for decryption
 * @return The decrypted bytes
 * @throws KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #2
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
protected byte[] decrypt(byte[] data) {

        try {
            SecretKey key = loadKey();

            byte[] ivBytes = new byte[16];                                                                  // 16 bytes is the IV size for AES256
            System.arraycopy(data, 0, ivBytes, 0, ivBytes.length);                                          // Get IV from data
            byte[] dataWithoutIV = new byte[data.length - ivBytes.length];                                  // Remove the room made for the IV
            System.arraycopy(data, ivBytes.length, dataWithoutIV, 0, dataWithoutIV.length);                 // Then the encrypted data

            PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
            cipher.init(false, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));

            return cipherData(cipher, dataWithoutIV);
        }
        catch(InvalidCipherTextException e) {
            Log.e(TAG, "Can't decrypt data", e);
        }
        return null;
    }
 
Example #3
Source File: SensitiveDataPreApi23.java    From android-java-connect-rest-sample with MIT License 6 votes vote down vote up
protected byte[] encrypt(byte[] data) {
    // 16 bytes is the IV size for AES256
    try {
        SecretKey key = loadKey();

        // Random IV
        SecureRandom rng = new SecureRandom();
        byte[] ivBytes = new byte[16];                                                                  // 16 bytes is the IV size for AES256
        rng.nextBytes(ivBytes);

        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(true, new ParametersWithIV(new KeyParameter(key.getEncoded()), ivBytes));

        byte[] encryptedData = cipherData(cipher, data);
        byte[] encryptedDataWithIV = new byte[encryptedData.length + ivBytes.length];                   // Make room for IV
        System.arraycopy(ivBytes, 0, encryptedDataWithIV, 0, ivBytes.length);                           // Add IV
        System.arraycopy(encryptedData, 0, encryptedDataWithIV, ivBytes.length, encryptedData.length);  // Then the encrypted data
        return encryptedDataWithIV;
    }
    catch(InvalidCipherTextException e) {
        Log.e(TAG, "Can't encrypt data", e);
    }
    return null;
}
 
Example #4
Source File: KeyCrypterScrypt.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt    The data to decrypt
 * @param aesKey           The AES key to use for decryption
 * @return                 The decrypted bytes
 * @throws                 KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #5
Source File: KeyCrypterScrypt.java    From GreenBits with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #6
Source File: Cryptograph.java    From AndroidAPS with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] produceCCMTag(byte[] nonce, byte[] payload, byte[] header, byte[] key) {
    TwofishEngine engine = new TwofishEngine();
    engine.init(true, new KeyParameter(key));
    byte[] initializationVector = new byte[engine.getBlockSize()];
    engine.processBlock(produceIV(nonce, (short) payload.length), 0, initializationVector, 0);
    CBCBlockCipher cbc = new CBCBlockCipher(new TwofishEngine());
    cbc.init(true, new ParametersWithIV(new KeyParameter(key), initializationVector));
    byte[] processedHeader = blockCipherZeroPad(processHeader(header));
    byte[] processedPayload = blockCipherZeroPad(payload);
    byte[] combine = combine(processedHeader, blockCipherZeroPad(processedPayload));
    byte[] result = new byte[combine.length];
    for (int i = 0; i < combine.length / 16; i++)
        cbc.processBlock(combine, i * 16, result, i * 16);
    byte[] result2 = new byte[8];
    System.arraycopy(result, result.length - 16, result2, 0, 8);
    byte[] ctr = new byte[engine.getBlockSize()];
    engine.processBlock(produceCTRBlock(nonce, (short) 0), 0, ctr, 0);
    return byteArrayXOR(result2, ctr);
}
 
Example #7
Source File: aes.java    From bitshares_wallet with MIT License 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear,0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;

}
 
Example #8
Source File: aes.java    From bitshares_wallet with MIT License 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 32 && iv.length == 16);
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf   = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example #9
Source File: AESEncrypt.java    From nuls with MIT License 6 votes vote down vote up
public static byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws CryptoException {
    Util.checkNotNull(dataToDecrypt);
    Util.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 #10
Source File: AESEncrypt.java    From nuls with MIT License 6 votes vote down vote up
public static EncryptedData encrypt(byte[] plainBytes, byte[] iv, KeyParameter aesKey) throws RuntimeException {
    Util.checkNotNull(plainBytes);
    Util.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 #11
Source File: Cryptograph.java    From SightRemote with GNU General Public License v3.0 6 votes vote down vote up
public static byte[] produceCCMTag(byte[] nonce, byte[] payload, byte[] header, byte[] key) {
    TwofishEngine engine = new TwofishEngine();
    engine.init(true, new KeyParameter(key));
    byte[] initializationVector = new byte[engine.getBlockSize()];
    engine.processBlock(produceIV(nonce, (short) payload.length), 0, initializationVector, 0);
    CBCBlockCipher cbc = new CBCBlockCipher(new TwofishEngine());
    cbc.init(true, new ParametersWithIV(new KeyParameter(key), initializationVector));
    byte[] processedHeader = blockCipherZeroPad(processHeader(header));
    byte[] processedPayload = blockCipherZeroPad(payload);
    byte[] combine = combine(processedHeader, blockCipherZeroPad(processedPayload));
    byte[] result = new byte[combine.length];
    for (int i = 0; i < combine.length / 16; i++) cbc.processBlock(combine, i * 16, result, i * 16);
    byte[] result2 = new byte[8];
    System.arraycopy(result, result.length - 16, result2, 0, 8);
    byte[] ctr = new byte[engine.getBlockSize()];
    engine.processBlock(produceCTRBlock(nonce, (short) 0), 0, ctr, 0);
    return byteArrayXOR(result2, ctr);
}
 
Example #12
Source File: KeyCrypterScrypt.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param dataToDecrypt    The data to decrypt
 * @param aesKey           The AES key to use for decryption
 * @return                 The decrypted bytes
 * @throws                 KeyCrypterException if bytes could not be decrypted
 */
@Override
public byte[] decrypt(EncryptedData dataToDecrypt, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(dataToDecrypt);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = dataToDecrypt.encryptedBytes;
        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 KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #13
Source File: KeyCrypterScrypt.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #14
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear,0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;

}
 
Example #15
Source File: aes.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 32 && iv.length == 16);
    try
    {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf   = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return null;
}
 
Example #16
Source File: KeyCrypterScrypt.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Password based encryption using AES - CBC 256 bits.
 */
@Override
public EncryptedData encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(plainBytes);
    checkNotNull(aesKey);

    try {
        // Generate iv - each encryption call has a different iv.
        byte[] iv = new byte[BLOCK_LENGTH];
        secureRandom.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 KeyCrypterException("Could not encrypt bytes.", e);
    }
}
 
Example #17
Source File: aes.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer encrypt(byte[] key, byte[] iv, byte[] plaintext) {
    assert (key.length == 64 && iv.length == 32);
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));

        cipher.init(true, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] outBuf = new byte[cipher.getOutputSize(plaintext.length)];
        int processed = cipher.processBytes(plaintext, 0, plaintext.length, outBuf, 0);
        processed += cipher.doFinal(outBuf, processed);

        ByteBuffer byteBuffer = ByteBuffer.allocate(processed);
        byteBuffer.put(outBuf, 0, processed);
        return byteBuffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #18
Source File: aes.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
public static ByteBuffer decrypt(byte[] key, byte[] iv, byte[] cipertext) {
    try {
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
        cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv));
        byte[] clear = new byte[cipher.getOutputSize(cipertext.length)];
        int len = cipher.processBytes(cipertext, 0, cipertext.length, clear, 0);
        len += cipher.doFinal(clear, len);
        ByteBuffer byteBuffer = ByteBuffer.allocate(len);
        byteBuffer.put(clear, 0, len);
        return byteBuffer;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}
 
Example #19
Source File: Salsa20.java    From openkeepass with Apache License 2.0 5 votes vote down vote up
private void initialize(byte[] protectedStreamKey) {
    byte[] salsaKey = Sha256.hash(protectedStreamKey);

    try {
        salsa20Engine = new Salsa20Engine();
        salsa20Engine.init(true, new ParametersWithIV(new KeyParameter(salsaKey), Hex.decode(SALSA20IV)));
    } catch (Exception e) {
        throw new UnsupportedOperationException("Could not find provider '" + SALSA20_ALGORITHM + "'", e);
    }
}
 
Example #20
Source File: ECKey.java    From tron-wallet-android with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

  if (privKey == null) {
    throw new MissingPrivateKeyException();
  }
  if (!(privKey instanceof BCECPrivateKey)) {
    throw new UnsupportedOperationException("Cannot use the private " +
        "key as an AES key");
  }

  AESFastEngine engine = new AESFastEngine();
  SICBlockCipher ctrEngine = new SICBlockCipher(engine);

  KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray((
      (BCECPrivateKey) privKey).getD()));
  ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

  ctrEngine.init(false, params);

  int i = 0;
  byte[] out = new byte[cipher.length];
  while (i < cipher.length) {
    ctrEngine.processBlock(cipher, i, out, i);
    i += engine.getBlockSize();
    if (cipher.length - i < engine.getBlockSize()) {
      break;
    }
  }

  // process left bytes
  if (cipher.length - i > 0) {
    byte[] tmpBlock = new byte[16];
    System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
    ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
    System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
  }

  return out;
}
 
Example #21
Source File: KeyCrypterScrypt.java    From bitherj with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt bytes previously encrypted with this class.
 *
 * @param privateKeyToDecode The private key to decrypt
 * @param aesKey             The AES key to use for decryption
 * @return The decrypted bytes
 * @throws KeyCrypterException if bytes could not be decoded to a valid key
 */
@Override
public byte[] decrypt(EncryptedPrivateKey privateKeyToDecode, KeyParameter aesKey) throws KeyCrypterException {
    checkNotNull(privateKeyToDecode);
    checkNotNull(aesKey);

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

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

        byte[] cipherBytes = privateKeyToDecode.getEncryptedBytes();
        int minimumSize = cipher.getOutputSize(cipherBytes.length);
        byte[] outputBuffer = new byte[minimumSize];
        int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, outputBuffer, 0);
        int length2 = cipher.doFinal(outputBuffer, length1);
        int actualLength = length1 + length2;

        byte[] decryptedBytes = new byte[actualLength];
        System.arraycopy(outputBuffer, 0, decryptedBytes, 0, actualLength);

        Utils.wipeBytes(outputBuffer);

        return decryptedBytes;
    } catch (Exception e) {
        throw new KeyCrypterException("Could not decrypt bytes", e);
    }
}
 
Example #22
Source File: ECKeySecp256k1.java    From aion with MIT License 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }

    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key =
            new KeyParameter(
                    BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #23
Source File: Encryption.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create an encrypted output stream from an unencrypted output stream
 */
public static OutputStream getEncryptedOutputStream (OutputStream decryptedOutputStream, byte[] keyData, byte[] ivData) {
    final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(keyData), ivData);
    PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    pbbc.init(true, keyAndIV);
    return new CipherOutputStream(decryptedOutputStream, pbbc);
}
 
Example #24
Source File: Encryption.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Create a decrypted input stream from an encrypted one
 */
public static InputStream getDecryptedInputStream (InputStream encryptedInputStream, byte[] keyData, byte[] ivData) {
    final ParametersWithIV keyAndIV = new ParametersWithIV(new KeyParameter(keyData), ivData);
    PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    pbbc.init(false, keyAndIV);
    return new CipherInputStream(encryptedInputStream, pbbc);
}
 
Example #25
Source File: Salsa20StreamEncryptor.java    From KeePassJava2 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Salsa20 engine
 *
 * @param key the key to use
 * @return an initialized Salsa20 engine
 */
@SuppressWarnings("WeakerAccess")
public static Salsa20Engine createSalsa20(byte[] key) {
    MessageDigest md = Encryption.getMessageDigestInstance();
    KeyParameter keyParameter = new KeyParameter(md.digest(key));
    ParametersWithIV ivParameter = new ParametersWithIV(keyParameter, SALSA20_IV);
    Salsa20Engine engine = new Salsa20Engine();
    engine.init(true, ivParameter);
    return engine;
}
 
Example #26
Source File: IoUtil.java    From OpenYOLO-Android with Apache License 2.0 5 votes vote down vote up
static PaddedBufferedBlockCipher createAes128CtrPkcs7PaddingCipher(
        boolean encrypting,
        byte[] iv,
        byte[] key) {
    AESEngine aes = new AESEngine();
    SICBlockCipher aesCtr = new SICBlockCipher(aes);
    PaddedBufferedBlockCipher aesCtrPkcs7 =
            new PaddedBufferedBlockCipher(aesCtr, new PKCS7Padding());
    aesCtrPkcs7.init(encrypting, new ParametersWithIV(new KeyParameter(key), iv));

    return aesCtrPkcs7;
}
 
Example #27
Source File: ECKey.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private " +
                "key as an AES key");
    }

    AESEngine engine = new AESEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray((
            (BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize()) {
            break;
        }
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #28
Source File: Crypto.java    From KeePassJava2 with Apache License 2.0 2 votes vote down vote up
/**
 * Get a cipher
 *
 * @param mode encryption or decryption
 * @param iv   a 16 byte iv
 * @return an initialised Cipher
 */
PaddedBufferedBlockCipher getCipher(CMode mode, byte[] iv) {
    PaddedBufferedBlockCipher result = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));
    result.init(mode.getEncrypt(), new ParametersWithIV(new KeyParameter(getKey()), iv));
    return result;
}