List of usage examples for javax.crypto CipherOutputStream close
public void close() throws IOException
From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java
private static void encryptFile(File file, EncryptedFormInformation formInfo) throws IOException, EncryptionException { File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc"); if (encryptedFile.exists() && !encryptedFile.delete()) { throw new IOException( "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?"); }//w w w .j a v a 2s .co m // add elementSignatureSource for this file... formInfo.appendFileSignatureSource(file); RandomAccessFile randomAccessFile = null; CipherOutputStream cipherOutputStream = null; try { Cipher c = formInfo.getCipher(); randomAccessFile = new RandomAccessFile(encryptedFile, "rws"); ByteArrayOutputStream encryptedData = new ByteArrayOutputStream(); cipherOutputStream = new CipherOutputStream(encryptedData, c); InputStream fin = new FileInputStream(file); byte[] buffer = new byte[2048]; int len = fin.read(buffer); while (len != -1) { cipherOutputStream.write(buffer, 0, len); len = fin.read(buffer); } fin.close(); cipherOutputStream.flush(); cipherOutputStream.close(); randomAccessFile.write(encryptedData.toByteArray()); Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName()); } catch (Exception e) { String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName(); Log.e(t, msg, e); e.printStackTrace(); throw new EncryptionException(msg, e); } finally { IOUtils.closeQuietly(cipherOutputStream); if (randomAccessFile != null) { randomAccessFile.close(); } } }
From source file:sec_algo.commonenc.java
/** * Encrypts the AES key to a file using an RSA public key *///from w w w. ja v a2 s . c o m public void saveKey(File out, File publicKeyFile) { try { // read public key to be used to encrypt the AES key byte[] encodedKey = new byte[(int) publicKeyFile.length()]; new FileInputStream(publicKeyFile).read(encodedKey); // create public key X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pk = kf.generatePublic(publicKeySpec); // write AES key pkCipher.init(Cipher.ENCRYPT_MODE, pk); CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher); os.write(key); os.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java
public void encrypt(InputStream in, OutputStream out) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { Cipher cipher = Cipher.getInstance(jcrypto.getAlgorithm()); if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) { IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES); cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec); } else {//from ww w .ja v a2 s. c o m cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes())); } CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { cos.write(buffer, 0, bytesRead); cos.flush(); } cos.close(); java.util.Arrays.fill(buffer, (byte) 0); }
From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java
private void encryptAndWriteAESKey(SecretKey aeskey, File dest) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException { Cipher keyc;//w ww. j av a 2 s. c om AssetManager am = getAssets(); InputStream in = am.open("mouflon_key.pub"); byte[] readFromFile = new byte[in.available()]; //TODO check that this is 294 bytes and replace with a constant. in.available is not guaranteed to return a useful value in.read(readFromFile); keyc = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); //ECB and CBC etc don't make sense for RSA, but the way this API is designed you have to specify something. KeyFactory kf = KeyFactory.getInstance("RSA"); KeySpec ks = new X509EncodedKeySpec(readFromFile); RSAPublicKey key = (RSAPublicKey) kf.generatePublic(ks); keyc.init(Cipher.ENCRYPT_MODE, key); //byte[] encrpytedKey = keyc.doFinal(aeskey.getEncoded()); FileOutputStream out = new FileOutputStream(dest); CipherOutputStream outcipher = new CipherOutputStream(out, keyc); outcipher.write(aeskey.getEncoded()); outcipher.close(); out.close(); }
From source file:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java
public void encryptStream() throws IOException { if (cipherMode != Cipher.ENCRYPT_MODE) throw new IllegalStateException("can not call encrypt, check cipher mode"); out.write(salt, 0, SALT_NUMBER_BITES); byte v[] = new byte[4]; //*** writeInt v[0] = (byte) (0xff & (iterations >> 24)); v[1] = (byte) (0xff & (iterations >> 16)); v[2] = (byte) (0xff & (iterations >> 8)); v[3] = (byte) (0xff & iterations); out.write(v);/*from www . j a v a2 s . co m*/ out.flush(); CipherOutputStream cos = new CipherOutputStream(out, cipher); // Read from the input and write to the encrypting output stream byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { cos.write(buffer, 0, bytesRead); } cos.flush(); cos.close(); out.close(); in.close(); }
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 */// ww w.j a v 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:org.grycap.gpf4med.security.FileEncryptionProvider.java
/** * Encrypts the message read from the specified input stream and writes the cipher text to the * specified output stream.//from www . ja va 2 s. c o m * @param fis input stream from where to read the plain text message. * @param fos output stream to where the cipher text is written. * @throws Exception if an error occurs in the execution of the operation. */ public void encrypt(final InputStream fis, final OutputStream fos) throws Exception { CipherOutputStream cos = null; try { cos = new CipherOutputStream(fos, encryptCipher); final byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fis.read(buffer)) >= 0) { cos.write(buffer, 0, bytesRead); } cos.flush(); } finally { try { fis.close(); } catch (Exception ignore) { } try { cos.close(); } catch (Exception ignore) { } } }
From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java
/** * Decrypts the cipher text read from the specified input stream and writes the decrypted message to * the specified output stream./* ww w .j a v a2 s.c o m*/ * @param inputStream input stream from where to read the cipher text. * @param outputStream output stream to where the decrypted message is written. * @throws Exception if an error occurs in the execution of the operation. */ public void decrypt(final InputStream fis, final OutputStream fos) throws Exception { CipherOutputStream cos = null; try { cos = new CipherOutputStream(fos, decryptCipher); final byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fis.read(buffer)) >= 0) { cos.write(buffer, 0, bytesRead); } cos.flush(); } finally { try { fis.close(); } catch (Exception ignore) { } try { cos.close(); } catch (Exception ignore) { } } }
From source file:net.tawacentral.roger.secrets.FileUtils.java
/** * Returns an encrypted json stream representing the user's secrets. * * @param cipher/*from w ww . j av a 2s . c om*/ * The encryption cipher to use with the file. * @param secrets * The list of secrets. * @return byte array of secrets * @throws IOException * if any error occurs */ public static byte[] toEncryptedJSONSecretsStream(Cipher cipher, ArrayList<Secret> secrets) throws IOException { CipherOutputStream output = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { output = new CipherOutputStream(baos, cipher); output.write(FileUtils.toJSONSecrets(secrets).toString().getBytes("UTF-8")); } catch (Exception e) { Log.e(LOG_TAG, "toEncryptedJSONSecretsStream", e); throw new IOException("toEncryptedJSONSecretsStream failed: " + e.getMessage()); } finally { try { if (null != output) output.close(); } catch (IOException ex) { } } return baos.toByteArray(); }
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 ww . j a va 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; }