Example usage for javax.crypto CipherInputStream CipherInputStream

List of usage examples for javax.crypto CipherInputStream CipherInputStream

Introduction

In this page you can find the example usage for javax.crypto CipherInputStream CipherInputStream.

Prototype

public CipherInputStream(InputStream is, Cipher c) 

Source Link

Document

Constructs a CipherInputStream from an InputStream and a Cipher.

Usage

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public final Object decryptObjFromInputStream(final InputStream is)
        throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchPaddingException, IOException, ClassNotFoundException {
    ready();//from  w  w w .  ja va  2 s .  c  o  m
    activecrypts++;
    try {
        final int saltsize = is.read();
        final byte[] salt;
        if (saltsize > 0) {
            salt = new byte[saltsize];
            is.read(salt);
        } else
            salt = null;
        ObjectInputStream ois = null;
        try {
            ois = is instanceof ObjectInputStream ? (ObjectInputStream) is
                    : new ObjectInputStream(new CipherInputStream(is, crypter.getDcipher(salt)));
            return ois.readObject();
        } finally {
            if (ois != null) {
                ois.close();
                ois = null;
            }
        }
    } finally {
        activecrypts--;
    }
}

From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.internal.EncryptedCachedDiskStringsTable.java

/***
 * Simulates random access to the tempfile even if not supported due to
 * encryption and/or compression/*from w w  w. j a  va  2  s. c o m*/
 * 
 * @param position
 * @throws IOException
 */
private void accessTempFile(long position) throws IOException {
    if ((position == 0L) || (position < this.currentPos)) { // in those cases we have to read from scratch
        this.in = new FileInputStream(this.tempFile);
        if (this.ca != null) {
            // decrypt
            this.in = new CipherInputStream(this.in, this.ciDecrypt);
        }
        if (this.compressTempFile) { // decompress it
            this.in = new GZIPInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
        } else { // configure a buffer for reading it
            this.in = new BufferedInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
        }
        this.currentPos = 0L;
    } else if (position > this.currentPos) {
        this.in.skip(position - this.currentPos);
        this.currentPos = position; // attention needs to be updated after read!
    }

}

From source file:org.opendatakit.briefcase.util.FileSystemUtils.java

private static final void decryptFile(EncryptionInformation ei, File original, File unencryptedDir)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    InputStream fin = null;// w ww .  j  a  v  a  2  s .  co  m
    OutputStream fout = null;

    try {
        if (original == null) {
            // special case -- user marked-as-complete an encrypted file on a pre-1.4.5 ODK Aggregate
            // need to get a Cipher to update the cipher initialization vector. 
            ei.getCipher("missing.enc");
            logger.info("Missing file (pre-ODK Aggregate 1.4.5 mark-as-complete on server)");
            return;
        }

        String name = original.getName();
        if (!name.endsWith(ENCRYPTED_FILE_EXTENSION)) {
            String errMsg = "Unexpected non-" + ENCRYPTED_FILE_EXTENSION + " extension " + name
                    + " -- ignoring file";
            throw new IllegalArgumentException(errMsg);
        }
        name = name.substring(0, name.length() - ENCRYPTED_FILE_EXTENSION.length());
        File decryptedFile = new File(unencryptedDir, name);

        Cipher c = ei.getCipher(name);

        // name is now the decrypted file name
        // if it ends in ".missing" then the file
        // was not available and the administrator
        // marked it as complete on the SubmissionAdmin
        // page.
        if (name.endsWith(MISSING_FILE_EXTENSION)) {
            logger.info("Missing file (ODK Aggregate 1.4.5 and higher):" + original.getName());
            return;
        }

        fin = new FileInputStream(original);
        fin = new CipherInputStream(fin, c);

        fout = new FileOutputStream(decryptedFile);
        byte[] buffer = new byte[2048];
        int len = fin.read(buffer);
        while (len != -1) {
            fout.write(buffer, 0, len);
            len = fin.read(buffer);
        }
        fout.flush();
        logger.info("Decrpyted:" + original.getName() + " -> " + decryptedFile.getName());
    } finally {
        if (fin != null) {
            try {
                fin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#decryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///from   ww  w. java 2s. c o m
public synchronized FileSecurityResponse decryptFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#decryptFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Cipher cipher = Cipher.getInstance(fileSecurityConfig.getEncryptionAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());

            if (DEBUG) {
                DEBUGGER.debug("Cipher: {}", cipher);
            }

            IOUtils.write(
                    IOUtils.toByteArray(
                            new CipherInputStream(new FileInputStream(request.getEncryptedFile()), cipher)),
                    new FileOutputStream(request.getDecryptedFile()));

            if ((request.getEncryptedFile().exists()) && (request.getEncryptedFile().length() != 0)) {
                response.setSignedFile(request.getEncryptedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (NoSuchPaddingException nspx) {
        ERROR_RECORDER.error(nspx.getMessage(), nspx);

        throw new FileSecurityException(nspx.getMessage(), nspx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.DECRYPTFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

@SuppressWarnings("unchecked")
private HashMap<String, String> readAndDecryptStorage(KeyStore keyStore) throws SecureLocalStorageException {

    try {//ww w .ja  v a  2s  .  co  m
        // obtain encrypted key
        SecretKey key = getSecretKey(keyStore);

        FileInputStream fis = _cordova.getActivity().openFileInput(SECURELOCALSTORAGEFILE);
        ArrayList<Byte> values = new ArrayList<Byte>();
        try {

            Cipher output = Cipher.getInstance("DES");
            output.init(Cipher.DECRYPT_MODE, key);

            CipherInputStream cipherInputStream = new CipherInputStream(fis, output);
            try {

                int nextByte;
                while ((nextByte = cipherInputStream.read()) != -1) {
                    values.add((byte) nextByte);
                }
            } finally {
                cipherInputStream.close();
            }
        } finally {
            fis.close();
        }

        byte[] bytes = new byte[values.size()];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = values.get(i);
        }

        HashMap<String, String> hashMap;
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        try {
            hashMap = (HashMap<String, String>) ois.readObject();
        } finally {
            ois.close();
        }
        return hashMap;
    } catch (Exception e) {
        Log.e("SecureStorage", "Write", e);
        throw new SecureLocalStorageException("Error decrypting storage", e);
    }
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

/**
 * Returns an updated object where the object content input stream contains the decrypted contents.
 *
 * @param object//  ww  w. ja v a  2s.  co  m
 *      The object whose contents are to be decrypted.
 * @param instruction
 *      The instruction that will be used to decrypt the object data.
 * @return
 *      The updated object where the object content input stream contains the decrypted contents.
 */
public static StorageObject decryptObjectUsingInstruction(StorageObject object,
        EncryptionInstruction instruction) {
    StorageObjectInputStream objectContent = object.getObjectContent();
    InputStream decryptedInputStream = new CipherInputStream(objectContent, instruction.getSymmetricCipher());
    object.setObjectContent(new StorageObjectInputStream(decryptedInputStream, objectContent.getHttpRequest()));
    return object;
}

From source file:com.microsoft.azure.storage.blob.CloudBlobClientEncryptionTests.java

@Test
public void testBlockBlobValidateEncryption() throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, StorageException, IOException, InvalidAlgorithmParameterException,
        URISyntaxException, InterruptedException, ExecutionException {
    int size = 5 * 1024 * 1024;
    byte[] buffer = TestHelper.getRandomBuffer(size);

    CloudBlockBlob blob = container.getBlockBlobReference("blob1");

    // Create the Key to be used for wrapping.
    SymmetricKey aesKey = TestHelper.getSymmetricKey();

    // Create the encryption policy to be used for upload.
    BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

    // Set the encryption policy on the request options.
    BlobRequestOptions uploadOptions = new BlobRequestOptions();
    uploadOptions.setEncryptionPolicy(uploadPolicy);

    // Upload the encrypted contents to the blob.
    ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
    blob.upload(stream, size, null, uploadOptions, null);

    // Encrypt locally.
    String metadata = blob.getMetadata().get(Constants.EncryptionConstants.BLOB_ENCRYPTION_DATA);
    BlobEncryptionData encryptionData = BlobEncryptionData.deserialize(metadata);

    Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptionData.getContentEncryptionIV());

    byte[] contentEncryptionKey = aesKey.unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
            encryptionData.getWrappedContentKey().getAlgorithm()).get();
    SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES");

    myAes.init(Cipher.ENCRYPT_MODE, keySpec, ivParameterSpec);

    CipherInputStream encryptedStream = new CipherInputStream(new ByteArrayInputStream(buffer), myAes);

    // Download the encrypted contents from the blob.
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    blob.download(outputStream);// w w w  .j a  va  2s . c  o  m

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
    for (int i = 0; i < outputStream.size(); i++) {
        assertEquals(encryptedStream.read(), inputStream.read());
    }

    encryptedStream.close();
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Decrypts the given input stream into the given output stream.
 */// ww  w. jav  a2s  .  c om
protected void decrypt(InputStream in, OutputStream out) throws IOException {
    byte[] magic = new byte[FILE_MAGIC.length];
    IOUtils.read(in, magic);
    if (!Arrays.equals(magic, FILE_MAGIC)) {
        throw new IOException("Invalid file (bad magic)");
    }
    DataInputStream data = new DataInputStream(in);
    byte magicvers = data.readByte();
    if (magicvers != FILE_VERSION_1) {
        throw new IOException("Invalid file (bad version)");
    }

    byte usepb = data.readByte();
    if (usepb == USE_PBKDF2) {
        if (!usePBKDF2) {
            throw new NuxeoException("File requires PBKDF2 password");
        }
    } else if (usepb == USE_KEYSTORE) {
        if (usePBKDF2) {
            throw new NuxeoException("File requires keystore");
        }
    } else {
        throw new IOException("Invalid file (bad use)");
    }

    try {
        // secret key
        Key secret;
        if (usePBKDF2) {
            // read salt first
            int saltLen = data.readInt();
            if (saltLen <= 0 || saltLen > MAX_SALT_LEN) {
                throw new NuxeoException("Invalid salt length: " + saltLen);
            }
            byte[] salt = new byte[saltLen];
            data.read(salt, 0, saltLen);
            secret = generateSecretKey(salt);
        } else {
            secret = getSecretKey();
        }

        // read IV
        int ivLen = data.readInt();
        if (ivLen <= 0 || ivLen > MAX_IV_LEN) {
            throw new NuxeoException("Invalid IV length: " + ivLen);
        }
        byte[] iv = new byte[ivLen];
        data.read(iv, 0, ivLen);

        // cipher
        Cipher cipher;
        cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));

        // read the encrypted data
        try (InputStream cipherIn = new CipherInputStream(in, cipher)) {
            IOUtils.copy(cipherIn, out);
        } catch (IOException e) {
            Throwable cause = e.getCause();
            if (cause != null && cause instanceof BadPaddingException) {
                throw new NuxeoException(cause.getMessage(), e);
            }
        }
    } catch (GeneralSecurityException e) {
        throw new NuxeoException(e);
    }
}

From source file:net.tawacentral.roger.secrets.FileUtils.java

/**
 * See previous method for description.//from  ww  w . j  a va 2  s .  c  om
 * 
 * @param context Activity context in which the load is called.
 * @param cipher Decryption cipher for old encryption.
 * @param fileName Name of file to be loaded
 * @return A list of loaded secrets.
 */
@SuppressWarnings("unchecked")
public static ArrayList<Secret> loadSecretsV1(Context context, Cipher cipher, String fileName) {
    Log.d(LOG_TAG, "FileUtils.loadSecretsV1");
    if (null == cipher)
        return null;

    ArrayList<Secret> secrets = null;
    ObjectInputStream input = null;

    try {
        InputStream fis = SECRETS_FILE_NAME_SDCARD.equals(fileName) ? new FileInputStream(fileName)
                : context.openFileInput(fileName);
        input = new ObjectInputStream(new CipherInputStream(fis, cipher));
        secrets = (ArrayList<Secret>) input.readObject();
    } catch (Exception ex) {
        Log.e(LOG_TAG, "loadSecretsV1", ex);
    } finally {
        try {
            if (null != input)
                input.close();
        } catch (IOException ex) {
        }
    }
    Log.d(LOG_TAG, "FileUtils.loadSecretsV1: done");
    return secrets;
}

From source file:com.stimulus.archiva.store.MessageStore.java

/** 
  * Get a raw input stream for a message
  * @param emailID The email ID//w  w w.  j a  va2  s . c o  m
  * @param decompress Should decompress message
  * @param decrypt Should decrypt message
  * @return An inputstream containing the message
  */
public InputStream getRawMessageInputStream(File messageFile, boolean decompress, boolean decrypt)
        throws IOException, MessageStoreException {
    if (messageFile == null)
        throw new MessageStoreException("assertion failure: null messageFileName", logger);

    InputStream is = new BufferedInputStream(new FileInputStream(messageFile));
    Cipher dcipher = null;
    if (decrypt) {
        try {

            dcipher = Cipher.getInstance(key.getAlgorithm());
            dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
        } catch (Exception e) {
            throw new MessageStoreException("failed to initialize cipher. cause:", e, logger);
        }
        is = new CipherInputStream(is, dcipher);
    }

    if (decompress)
        is = new GZIPInputStream(is);

    return is;
}