Search in sources :

Example 81 with CipherInputStream

use of javax.crypto.CipherInputStream in project accumulo by apache.

the class DefaultCryptoModule method getDecryptingInputStream.

@Override
public CryptoModuleParameters getDecryptingInputStream(CryptoModuleParameters params) throws IOException {
    log.trace("About to initialize decryption stream (new style)");
    if (params.getRecordParametersToStream()) {
        DataInputStream dataIn = new DataInputStream(params.getEncryptedInputStream());
        log.trace("About to read encryption parameters from underlying stream");
        String marker = dataIn.readUTF();
        if (marker.equals(ENCRYPTION_HEADER_MARKER_V1) || marker.equals(ENCRYPTION_HEADER_MARKER_V2)) {
            Map<String, String> paramsFromFile = new HashMap<>();
            // Read in the bulk of parameters
            int paramsCount = dataIn.readInt();
            for (int i = 0; i < paramsCount; i++) {
                String key = dataIn.readUTF();
                String value = dataIn.readUTF();
                paramsFromFile.put(key, value);
            }
            // Set the cipher parameters
            String cipherSuiteFromFile = dataIn.readUTF();
            String algorithmNameFromFile = dataIn.readUTF();
            params.setCipherSuite(cipherSuiteFromFile);
            params.setKeyAlgorithmName(algorithmNameFromFile);
            // Read the secret key and initialization vector from the file
            int initVectorLength = dataIn.readInt();
            byte[] initVector = new byte[initVectorLength];
            dataIn.readFully(initVector);
            params.setInitializationVector(initVector);
            // Read the opaque ID and encrypted session key
            String opaqueId = dataIn.readUTF();
            params.setOpaqueKeyEncryptionKeyID(opaqueId);
            int encryptedSecretKeyLength = dataIn.readInt();
            byte[] encryptedSecretKey = new byte[encryptedSecretKeyLength];
            dataIn.readFully(encryptedSecretKey);
            params.setEncryptedKey(encryptedSecretKey);
            if (params.getOverrideStreamsSecretKeyEncryptionStrategy()) {
                // Merge in options from file selectively
                for (String name : paramsFromFile.keySet()) {
                    if (!name.equals(Property.CRYPTO_SECRET_KEY_ENCRYPTION_STRATEGY_CLASS.getKey())) {
                        params.getAllOptions().put(name, paramsFromFile.get(name));
                    }
                }
                params.setKeyEncryptionStrategyClass(params.getAllOptions().get(Property.CRYPTO_SECRET_KEY_ENCRYPTION_STRATEGY_CLASS.getKey()));
            } else {
                params = CryptoModuleFactory.fillParamsObjectFromStringMap(params, paramsFromFile);
            }
            SecretKeyEncryptionStrategy keyEncryptionStrategy = CryptoModuleFactory.getSecretKeyEncryptionStrategy(params.getKeyEncryptionStrategyClass());
            params = keyEncryptionStrategy.decryptSecretKey(params);
            if (marker.equals(ENCRYPTION_HEADER_MARKER_V2))
                params.setBlockStreamSize(dataIn.readInt());
            else
                params.setBlockStreamSize(0);
        } else {
            log.trace("Read something off of the encrypted input stream that was not the encryption header marker, so pushing back bytes and returning the given stream");
            // Push these bytes back on to the stream. This method is a bit roundabout but isolates our code
            // from having to understand the format that DataOuputStream uses for its bytes.
            ByteArrayOutputStream tempByteOut = new ByteArrayOutputStream();
            DataOutputStream tempOut = new DataOutputStream(tempByteOut);
            tempOut.writeUTF(marker);
            byte[] bytesToPutBack = tempByteOut.toByteArray();
            PushbackInputStream pushbackStream = new PushbackInputStream(params.getEncryptedInputStream(), bytesToPutBack.length);
            pushbackStream.unread(bytesToPutBack);
            params.setPlaintextInputStream(pushbackStream);
            return params;
        }
    }
    // We validate here after reading parameters from the stream, not at the top of the function.
    boolean allParamsOK = validateParamsObject(params, Cipher.DECRYPT_MODE);
    if (!allParamsOK) {
        log.error("CryptoModuleParameters object failed validation for decrypt");
        throw new RuntimeException("CryptoModuleParameters object failed validation for decrypt");
    }
    Cipher cipher = DefaultCryptoModuleUtils.getCipher(params.getCipherSuite(), params.getSecurityProvider());
    try {
        initCipher(params, cipher, Cipher.DECRYPT_MODE);
    } catch (InvalidKeyException e) {
        log.error("Error when trying to initialize cipher with secret key");
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        log.error("Error when trying to initialize cipher with initialization vector");
        throw new RuntimeException(e);
    }
    InputStream blockedDecryptingInputStream = new CipherInputStream(params.getEncryptedInputStream(), cipher);
    if (params.getBlockStreamSize() > 0)
        blockedDecryptingInputStream = new BlockedInputStream(blockedDecryptingInputStream, cipher.getBlockSize(), params.getBlockStreamSize());
    log.trace("Initialized cipher input stream with transformation [{}]", params.getCipherSuite());
    params.setPlaintextInputStream(blockedDecryptingInputStream);
    return params;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CipherInputStream(javax.crypto.CipherInputStream) HashMap(java.util.HashMap) DataOutputStream(java.io.DataOutputStream) DataInputStream(java.io.DataInputStream) PushbackInputStream(java.io.PushbackInputStream) CipherInputStream(javax.crypto.CipherInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataInputStream(java.io.DataInputStream) InvalidKeyException(java.security.InvalidKeyException) PushbackInputStream(java.io.PushbackInputStream) Cipher(javax.crypto.Cipher)

Example 82 with CipherInputStream

use of javax.crypto.CipherInputStream in project Jartop by TheRedSpy15.

the class User method login.

final synchronized void login(String password, boolean loadWith256) throws IOException, InterruptedException {
    boolean loggedIn = true;
    final byte bruteForcePauseLength = 50;
    final byte maximumTries = 20;
    // Determining key size
    byte keySize;
    if (// 256
    loadWith256)
        // 256
        keySize = 32;
    else
        // 128
        keySize = 16;
    try {
        try {
            // Hashing
            final String hash = Hashing.sha256().hashString(password, Charsets.UTF_8).toString().substring(0, keySize);
            // Creating keys
            final byte[] key = hash.getBytes();
            final String transformation = "AES";
            final SecretKeySpec sks = new SecretKeySpec(key, transformation);
            // Creating cipher
            final Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, sks);
            // Streams
            final FileInputStream fileInputStream = new FileInputStream(getUserFile().getAbsoluteFile());
            final CipherInputStream cipherInputStream = new CipherInputStream(fileInputStream, cipher);
            try (ObjectInputStream objectInputStream = new ObjectInputStream(cipherInputStream)) {
                // Reading
                SealedObject sealedObject = (SealedObject) objectInputStream.readObject();
                Core.setUserData((User) sealedObject.getObject(cipher));
            } finally {
                // Closing streams
                fileInputStream.close();
                cipherInputStream.close();
            }
        } catch (NoSuchPaddingException | NoSuchAlgorithmException | ClassNotFoundException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        // assuming wrong password
        loggedIn = false;
        Core.getUAS().setFailedAttempts((byte) (Core.getUAS().getFailedAttempts() + 1));
        // secure delete
        if (Core.getUAS().getFailedAttempts() >= maximumTries) {
            Core.getUAS().secureDelete(Core.getUserData().getUserFile(), false);
        }
        // to slow down brute force attacks
        Core.getUserData().wait(bruteForcePauseLength);
        Logger.getAnonymousLogger().warning("Log in failed - likely wrong password");
        Notifications.create().title("Warning").text("Log in failed - likely wrong password").darkStyle().showWarning();
    }
    // Loading desktop
    if (loggedIn) {
        Parent desktopScene = FXMLLoader.load(Core.class.getResource("Desktop.fxml"));
        Core.getDesktop().setScene(new Scene(desktopScene));
        Core.getUserData().setGuest(false);
        Logger.getAnonymousLogger().info("Logged in successfully");
        Notifications.create().title("Notice").text("Logged in as " + getName()).darkStyle().showInformation();
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) Parent(javafx.scene.Parent) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) SealedObject(javax.crypto.SealedObject) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) Scene(javafx.scene.Scene) FileInputStream(java.io.FileInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) IOException(java.io.IOException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) Cipher(javax.crypto.Cipher) ObjectInputStream(java.io.ObjectInputStream)

Example 83 with CipherInputStream

use of javax.crypto.CipherInputStream in project Signal-Android by WhisperSystems.

the class EncryptedCoder method createEncryptedInputStream.

CipherInputStream createEncryptedInputStream(@NonNull byte[] masterKey, @NonNull File file) throws IOException {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(masterKey, "HmacSHA256"));
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] theirMagic = new byte[MAGIC_BYTES.length];
        byte[] theirRandom = new byte[32];
        byte[] theirEncryptedMagic = new byte[MAGIC_BYTES.length];
        StreamUtil.readFully(fileInputStream, theirMagic);
        StreamUtil.readFully(fileInputStream, theirRandom);
        if (!MessageDigest.isEqual(theirMagic, MAGIC_BYTES)) {
            throw new IOException("Not an encrypted cache file!");
        }
        byte[] iv = new byte[16];
        byte[] key = mac.doFinal(theirRandom);
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
        CipherInputStream inputStream = new CipherInputStream(fileInputStream, cipher);
        StreamUtil.readFully(inputStream, theirEncryptedMagic);
        if (!MessageDigest.isEqual(theirEncryptedMagic, MAGIC_BYTES)) {
            throw new IOException("Key change on encrypted cache file!");
        }
        return inputStream;
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
        throw new AssertionError(e);
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CipherInputStream(javax.crypto.CipherInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Mac(javax.crypto.Mac) FileInputStream(java.io.FileInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 84 with CipherInputStream

use of javax.crypto.CipherInputStream in project apex-malhar by apache.

the class AbstractFileOutputOperatorTest method checkCompressedFile.

private void checkCompressedFile(File file, List<Long> offsets, int startVal, int totalWindows, int totalRecords, SecretKey secretKey, byte[] iv) throws IOException {
    FileInputStream fis;
    InputStream gss = null;
    GZIPInputStream gis = null;
    BufferedReader br = null;
    Cipher cipher = null;
    if (secretKey != null) {
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivps);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    int numWindows = 0;
    try {
        fis = new FileInputStream(file);
        // fis.skip(startOffset);
        gss = fis;
        if (secretKey != null) {
            try {
                /*
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ivps = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivps);
            */
                gss = new CipherInputStream(fis, cipher);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        long startOffset = 0;
        for (long offset : offsets) {
            // Skip initial case in case file is not yet created
            if (offset == 0) {
                continue;
            }
            long limit = offset - startOffset;
            LimitInputStream lis = new LimitInputStream(gss, limit);
            // gis = new GZIPInputStream(fis);
            gis = new GZIPInputStream(lis);
            br = new BufferedReader(new InputStreamReader(gis));
            // br = new BufferedReader(new InputStreamReader(gss));
            String eline = "" + (startVal + numWindows * 2);
            int count = 0;
            String line;
            while ((line = br.readLine()) != null) {
                Assert.assertEquals("File line", eline, line);
                ++count;
                if ((count % totalRecords) == 0) {
                    ++numWindows;
                    eline = "" + (startVal + numWindows * 2);
                }
            }
            startOffset = offset;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            br.close();
        } else {
            if (gis != null) {
                gis.close();
            } else if (gss != null) {
                gss.close();
            }
        }
    }
    Assert.assertEquals("Total", totalWindows, numWindows);
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) LimitInputStream(com.google.common.io.LimitInputStream) CipherInputStream(javax.crypto.CipherInputStream) CompressionInputStream(org.apache.hadoop.io.compress.CompressionInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) LimitInputStream(com.google.common.io.LimitInputStream) FileInputStream(java.io.FileInputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) ConstraintViolationException(javax.validation.ConstraintViolationException) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedReader(java.io.BufferedReader) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 85 with CipherInputStream

use of javax.crypto.CipherInputStream in project cxf by apache.

the class CachedOutputStream method getInputStream.

public InputStream getInputStream() throws IOException {
    flush();
    if (inmem) {
        if (currentStream instanceof LoadingByteArrayOutputStream) {
            return ((LoadingByteArrayOutputStream) currentStream).createInputStream();
        } else if (currentStream instanceof ByteArrayOutputStream) {
            return new ByteArrayInputStream(((ByteArrayOutputStream) currentStream).toByteArray());
        } else {
            return null;
        }
    }
    try {
        InputStream fileInputStream = new TransferableFileInputStream(tempFile);
        streamList.add(fileInputStream);
        if (cipherTransformation != null) {
            fileInputStream = new CipherInputStream(fileInputStream, ciphers.getDecryptor()) {

                boolean closed;

                public void close() throws IOException {
                    if (!closed) {
                        super.close();
                        closed = true;
                    }
                }
            };
        }
        return fileInputStream;
    } catch (FileNotFoundException e) {
        throw new IOException("Cached file was deleted, " + e.toString());
    }
}
Also used : LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) LoadingByteArrayOutputStream(org.apache.cxf.helpers.LoadingByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

CipherInputStream (javax.crypto.CipherInputStream)102 Cipher (javax.crypto.Cipher)66 IOException (java.io.IOException)42 InputStream (java.io.InputStream)32 ByteArrayInputStream (java.io.ByteArrayInputStream)30 IvParameterSpec (javax.crypto.spec.IvParameterSpec)21 SecretKeySpec (javax.crypto.spec.SecretKeySpec)21 FileInputStream (java.io.FileInputStream)19 InvalidKeyException (java.security.InvalidKeyException)16 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)15 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)13 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 NullCipher (javax.crypto.NullCipher)11 DataInputStream (java.io.DataInputStream)9 RuntimeException (java.lang.RuntimeException)9 GeneralSecurityException (java.security.GeneralSecurityException)9 CipherOutputStream (javax.crypto.CipherOutputStream)8 BufferedInputStream (java.io.BufferedInputStream)7 Key (java.security.Key)7