List of usage examples for javax.crypto CipherOutputStream close
public void close() throws IOException
From source file:sec_algo.commonenc.java
public void encryptFile() { File encrypted = new File("demo2\\" + returnFileName() + "_encrypted." + returnFileExt()); byte[] temp, result; try {//from w ww . j a v a 2 s . c o m FileInputStream in = new FileInputStream(file); // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); // byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // IvParameterSpec ivspec = new IvParameterSpec(iv); aesCipher.init(Cipher.ENCRYPT_MODE, secretkey); CipherOutputStream os = new CipherOutputStream(new FileOutputStream(encrypted), aesCipher); long startTime = System.currentTimeMillis(); copy(in, os); long endTime = System.currentTimeMillis(); System.out.println("startTime - " + startTime); System.out.println("endTime - " + endTime); encryptTime = endTime - startTime; in.close(); os.close(); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.apache.synapse.securevault.BaseCipher.java
/** * Do cryptographic operation/* w ww.ja v a 2s.c om*/ * * @param inputStream Input Stream * @return result */ private byte[] doCipherOperation(byte[] inputStream) { InputStream sourceStream = new ByteArrayInputStream(inputStream); if (cipherInformation.getInType() != null) { try { sourceStream = EncodingHelper.decode(sourceStream, cipherInformation.getInType()); } catch (IOException e) { throw new SecureVaultException("IOError when decoding the input " + "stream for cipher ", e, log); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); CipherOutputStream out = new CipherOutputStream(baos, cipher); byte[] buffer = new byte[64]; int length; try { while ((length = sourceStream.read(buffer)) != -1) { out.write(buffer, 0, length); } } catch (IOException e) { throw new SecureVaultException("IOError when reading the input" + " stream for cipher ", e, log); } finally { try { sourceStream.close(); out.flush(); out.close(); } catch (IOException ignored) { // ignore exception } } if (cipherInformation.getOutType() != null) { return EncodingHelper.encode(baos, cipherInformation.getOutType()); } else { return baos.toByteArray(); } }
From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
private void generateKey(KeyStore keyStore) throws SecureLocalStorageException { try {// w ww .j a va2 s .c o m _key = null; SecretKey key = KeyGenerator.getInstance("DES").generateKey(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); try { oos.writeObject(key); } finally { oos.close(); } } finally { bos.close(); } // store key encrypted with keystore key pair KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore .getEntry(SECURELOCALSTORAGEALIAS, null); Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding"); input.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey()); FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEKEY, Context.MODE_PRIVATE); try { CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input); try { cipherOutputStream.write(bos.toByteArray()); } finally { cipherOutputStream.close(); } } finally { fos.close(); } } catch (Exception e) { Log.e("SecureStorage", "Read", e); throw new SecureLocalStorageException("Error generating key", e); } }
From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
private void writeAndEncryptStorage(KeyStore keyStore, HashMap<String, String> hashMap) throws SecureLocalStorageException { try {/*from ww w .j a va2s . co m*/ ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); try { oos.writeObject(hashMap); } finally { oos.close(); } } finally { bos.close(); } SecretKey key = getSecretKey(keyStore); Cipher input = Cipher.getInstance("DES"); input.init(Cipher.ENCRYPT_MODE, key); // encrypt the hashmap FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEFILE, Context.MODE_PRIVATE); try { CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input); try { cipherOutputStream.write(bos.toByteArray()); } finally { cipherOutputStream.flush(); cipherOutputStream.close(); } } finally { fos.flush(); fos.close(); } } catch (Exception e) { Log.e("SecureStorage", "Write", e); throw new SecureLocalStorageException("Error encrypting storage", e); } }
From source file:com.denel.facepatrol.MainActivity.java
private void decryptfile(Context mcontext, SecretKey key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { File infile = mcontext.getDatabasePath(dbname_en); InputStream fis = new FileInputStream(infile); File outfile = mcontext.getDatabasePath(dbname); // parent directory for his file if it doesn't exist, // in this case it returns a false. outfile.getParentFile().mkdirs();//from w w w . ja v a2 s . co m // This stream write the decrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream(outfile); // Length is 16 byte // Careful when taking user input!!! // http://stackoverflow.com/a/3452620/1188357 SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); // delete the encrypted file if (infile.exists()) { infile.delete(); } }
From source file:com.denel.facepatrol.MainActivity.java
private void encryptfile(Context mcontext, SecretKey key) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { // This will probably change when I will the database will be downloaded from the server boolean db_file_exists = mcontext.getDatabasePath(dbname).exists(); InputStream fis = null;//w ww . j av a 2s. com File infile = mcontext.getDatabasePath(dbname); // check if database file exists to prevent downloading the file each start if (db_file_exists) { fis = new FileInputStream(infile); } else { fis = mcontext.getAssets().open(dbname); } // This stream write the encrypted text. This stream will be wrapped by another stream. FileOutputStream fos = new FileOutputStream(mcontext.getDatabasePath(dbname_en).getAbsolutePath()); // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES"); // Create cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sks); // Wrap the output stream CipherOutputStream cos = new CipherOutputStream(fos, cipher); // Write bytes int b; byte[] d = new byte[8]; while ((b = fis.read(d)) != -1) { cos.write(d, 0, b); } // Flush and close streams. cos.flush(); cos.close(); fis.close(); // delete the decrypted file if (infile.exists()) { infile.delete(); } }
From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java
protected File createDataFile(InputStream data, String username, char[] password) throws IOException { try {/*from ww w . ja v a2 s .c o m*/ String fileName = UUID.randomUUID().toString(); File folder = new File(storageFolder, username); folder = new File(folder, fileName.substring(0, 2)); folder.mkdirs(); File file = new File(folder, fileName); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(username, password)); OutputStream fOut = new BufferedOutputStream(new FileOutputStream(file)); CipherOutputStream out = new CipherOutputStream(fOut, cipher); InputStream in = new BufferedInputStream(data); byte[] buffer = new byte[2048]; int readed; while ((readed = in.read(buffer)) != -1) { out.write(buffer, 0, readed); } in.close(); out.flush(); out.close(); fOut.flush(); fOut.close(); return file; } catch (Exception ex) { // TODO: better exception handling Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex); throw new RuntimeException(ex); } finally { data.close(); } }
From source file:craterdog.security.MessageCryptex.java
@Override public void encryptStream(SecretKey sharedKey, InputStream input, OutputStream output) throws IOException { logger.entry();/* w ww . j a v a2s. com*/ CipherOutputStream cipherOutput = null; byte[] buffer = new byte[2048]; try { logger.debug("Creating a special output stream to do the work..."); cipherOutput = encryptionOutputStream(sharedKey, output); logger.debug("Reading from the input and writing to the encrypting output stream..."); // Can't use IOUtils.copy(input, cipherOutput) here because need to purge buffer later... int bytesRead; while ((bytesRead = input.read(buffer)) != -1) { cipherOutput.write(buffer, 0, bytesRead); } cipherOutput.flush(); } finally { logger.debug("Purging any plaintext hanging around in memory..."); Arrays.fill(buffer, (byte) 0); if (cipherOutput != null) cipherOutput.close(); } logger.exit(); }
From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java
/** * Converts cart object into a String tuple. * * @param serializable cart/*w ww . j av a 2 s . com*/ * * @return string * * @throws CartTuplizationException when cannot convert to string tuple */ protected String toToken(final Serializable serializable) throws CartTuplizationException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); synchronized (desCipher) { Base64OutputStream base64EncoderStream = new Base64OutputStream(byteArrayOutputStream, true, Integer.MAX_VALUE, null); //will be split manually CipherOutputStream cipherOutputStream = new CipherOutputStream(base64EncoderStream, desCipher); ObjectOutputStream objectOutputStream = null; try { objectOutputStream = new ObjectOutputStream(cipherOutputStream); objectOutputStream.writeObject(serializable); objectOutputStream.flush(); objectOutputStream.close(); } catch (Throwable ioe) { LOG.error(MessageFormat.format("Unable to serialize object {0}", serializable), ioe); throw new CartTuplizationException(ioe); } finally { try { if (objectOutputStream != null) { objectOutputStream.close(); } cipherOutputStream.close(); base64EncoderStream.close(); byteArrayOutputStream.close(); } catch (IOException e) { LOG.error("Can not close stream", e); } } } return byteArrayOutputStream.toString(); }
From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java
/** * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#encryptFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest) *///from w w w . j av a 2 s. c o m public synchronized FileSecurityResponse encryptFile(final FileSecurityRequest request) throws FileSecurityException { final String methodName = IFileSecurityProcessor.CNAME + "#encryptFile(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.ENCRYPT_MODE, keyPair.getPrivate()); if (DEBUG) { DEBUGGER.debug("Cipher: {}", cipher); } CipherOutputStream cipherOut = new CipherOutputStream( new FileOutputStream(request.getEncryptedFile()), cipher); if (DEBUG) { DEBUGGER.debug("CipherOutputStream: {}", cipherOut); } byte[] data = IOUtils.toByteArray(new FileInputStream(request.getDecryptedFile())); IOUtils.write(data, cipherOut); cipherOut.flush(); cipherOut.close(); 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.ENCRYPTFILE); 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; }