List of usage examples for javax.crypto CipherOutputStream flush
public void flush() throws IOException
From source file:org.apache.synapse.commons.security.wrappers.CipherWrapper.java
/** * Returns the output of the cipher operation. * This expose the 'getSecret' abstraction and hide operation of the underlying cipher * * @param inputStream Input as a stream. This can be either cipher or plain text * @return Secret as String.This can be either cipher or plain text *//*from w w w. j av a 2 s . c o m*/ public String getSecret(InputStream inputStream) { InputStream sourceStream = null; if (cipherInformation.getInType() != null) { try { sourceStream = EncodingHelper.decode(inputStream, cipherInformation.getInType()); } catch (IOException e) { handleException("IOError when decoding the input stream for cipher ", e); } } else { sourceStream = inputStream; } 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) { handleException("IOError when reading the input stream for cipher ", e); } finally { try { sourceStream.close(); out.flush(); out.close(); } catch (IOException ignored) { // ignore exception } } String secret; if (cipherInformation.getOutType() != null) { secret = EncodingHelper.encode(baos, cipherInformation.getOutType()); } else { secret = baos.toString(); } return secret; }
From source file:de.schildbach.wallet.util.FingerprintHelper.java
@RequiresApi(api = Build.VERSION_CODES.M) public boolean encryptPassword(Cipher cipher, String password) { try {/*from w w w .java 2 s . c om*/ // Encrypt the text if (password.isEmpty()) { log.info("Password is empty"); return false; } if (cipher == null) { log.info("Could not create cipher"); return false; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher); byte[] bytes = password.getBytes(Charset.defaultCharset()); cipherOutputStream.write(bytes); cipherOutputStream.flush(); cipherOutputStream.close(); saveEncryptedPassword(encodeBytes(outputStream.toByteArray())); } catch (Throwable t) { log.info("Encryption failed " + t.getMessage()); return false; } return true; }
From source file:org.apache.synapse.securevault.BaseCipher.java
/** * Do cryptographic operation/*www .j av a 2 s. c o m*/ * * @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:craterdog.security.MessageCryptex.java
@Override public void encryptStream(SecretKey sharedKey, InputStream input, OutputStream output) throws IOException { logger.entry();/*from w ww . java 2 s. c o m*/ 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:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java
private void writeAndEncryptStorage(KeyStore keyStore, HashMap<String, String> hashMap) throws SecureLocalStorageException { try {/* www . ja v a 2 s .com*/ 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 ww . jav a 2s .c om*/ // 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;/*from w ww . j a v a 2 s . c o m*/ 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 w w w . j av a 2 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:org.apache.camel.converter.crypto.CryptoDataFormat.java
public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception { byte[] iv = getInitializationVector(exchange); Key key = getKey(exchange);/*from w w w .ja va 2 s . c o m*/ CipherOutputStream cipherStream = new CipherOutputStream(outputStream, initializeCipher(ENCRYPT_MODE, key, iv)); InputStream plaintextStream = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph); HMACAccumulator hmac = getMessageAuthenticationCode(key); if (plaintextStream != null) { inlineInitVector(outputStream, iv); byte[] buffer = new byte[bufferSize]; int read; try { while ((read = plaintextStream.read(buffer)) > 0) { cipherStream.write(buffer, 0, read); cipherStream.flush(); hmac.encryptUpdate(buffer, read); } // only write if there is data to write (IBM JDK throws exception if no data) byte[] mac = hmac.getCalculatedMac(); if (mac != null && mac.length > 0) { cipherStream.write(mac); } } finally { IOHelper.close(cipherStream, "cipher", LOG); } } }
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) */// w w w.j a v 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; }