List of usage examples for javax.crypto CipherOutputStream CipherOutputStream
public CipherOutputStream(OutputStream os, Cipher c)
From source file:de.schildbach.wallet.util.FingerprintHelper.java
@RequiresApi(api = Build.VERSION_CODES.M) public boolean encryptPassword(Cipher cipher, String password) { try {// w w w. ja va 2s. c o m // 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:com.microsoft.azure.storage.core.Utility.java
/** * Encrypts an input stream up to a given length. * Exits early if the encrypted data is longer than the abandon length. * //from w w w . ja v a 2s. c o m * @param sourceStream * A <code>InputStream</code> object that represents the stream to measure. * @param targetStream * A <code>ByteArrayOutputStream</code> object that represents the stream to write the encrypted data. * @param cipher * The <code>Cipher</code> to use to encrypt the data. * @param writeLength * The number of bytes to read and encrypt from the sourceStream. * @param abandonLength * The number of bytes to read before the analysis is abandoned. Set this value to <code>-1</code> to * force the entire stream to be read. This parameter is provided to support upload thresholds. * @return * The size of the encrypted stream, or -1 if the encrypted stream would be over the abandonLength. * @throws IOException * If an I/O error occurs. */ public static long encryptStreamIfUnderThreshold(final InputStream sourceStream, final ByteArrayOutputStream targetStream, Cipher cipher, long writeLength, long abandonLength) throws IOException { if (abandonLength < 0) { abandonLength = Long.MAX_VALUE; } if (!sourceStream.markSupported()) { throw new IllegalArgumentException(SR.INPUT_STREAM_SHOULD_BE_MARKABLE); } sourceStream.mark(Constants.MAX_MARK_LENGTH); if (writeLength < 0) { writeLength = Long.MAX_VALUE; } CipherOutputStream encryptStream = new CipherOutputStream(targetStream, cipher); int count = -1; long totalEncryptedLength = targetStream.size(); final byte[] retrievedBuff = new byte[Constants.BUFFER_COPY_LENGTH]; int nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); while (nextCopy > 0 && count != -1) { // Note: We are flushing the CryptoStream on every write here. This way, we don't end up encrypting more data than we intend here, if // we go over the abandonLength. encryptStream.write(retrievedBuff, 0, count); encryptStream.flush(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { // Abandon operation break; } nextCopy = (int) Math.min(retrievedBuff.length, writeLength - totalEncryptedLength); count = sourceStream.read(retrievedBuff, 0, nextCopy); } sourceStream.reset(); sourceStream.mark(Constants.MAX_MARK_LENGTH); encryptStream.close(); totalEncryptedLength = targetStream.size(); if (totalEncryptedLength > abandonLength) { totalEncryptedLength = -1; } return totalEncryptedLength; }
From source file:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java
/** * give a CipherOutputStream to encrypt data, if you want to encrypt data yourself * out must be given in class constructor * @return/*from w ww.j a va 2 s . c o m*/ */ public CipherOutputStream getCipherOutputStream() { if (out == null) throw new IllegalStateException("can not give intialised CipherOutputStream, check outputstream"); return new CipherOutputStream(out, cipher); }
From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java
@Override public CipherOutputStream getCipherOutputStream(File file, String outputFileName) throws SecrecyCipherStreamException, FileNotFoundException { Cipher c;//from w ww . j av a 2 s . c om try { c = Cipher.getInstance(encryptionMode); } catch (NoSuchAlgorithmException e) { throw new SecrecyCipherStreamException("Encryption algorithm not found!"); } catch (NoSuchPaddingException e) { throw new SecrecyCipherStreamException("Selected padding not found!"); } File headerFile = new File(vaultPath + FILE_HEADER_PREFIX + outputFileName); File outputFile = new File(vaultPath + "/" + outputFileName); byte[] fileEncryptionNonce = new byte[NONCE_LENGTH_BYTE]; byte[] fileNameNonce = new byte[NONCE_LENGTH_BYTE]; secureRandom.nextBytes(fileEncryptionNonce); secureRandom.nextBytes(fileNameNonce); try { c.init(Cipher.ENCRYPT_MODE, vaultFileEncryptionKey, new IvParameterSpec(fileNameNonce)); } catch (InvalidKeyException e) { throw new SecrecyCipherStreamException("Invalid encryption key!"); } catch (InvalidAlgorithmParameterException e) { throw new SecrecyCipherStreamException("Invalid algorithm parameter!"); } byte[] encryptedFileName; try { encryptedFileName = c.doFinal(file.getName().getBytes()); } catch (IllegalBlockSizeException e) { throw new SecrecyCipherStreamException("Illegal block size!"); } catch (BadPaddingException e) { throw new SecrecyCipherStreamException("Bad padding"); } FileHeader.Builder fileHeaderBuilder = FileHeader.newBuilder(); fileHeaderBuilder.setVersion(FILE_HEADER_VERSION); fileHeaderBuilder.setFileIV(ByteString.copyFrom(fileEncryptionNonce)); fileHeaderBuilder.setFileNameIV(ByteString.copyFrom(fileNameNonce)); fileHeaderBuilder.setEncryptedFileName(ByteString.copyFrom(encryptedFileName)); FileOutputStream headerOutputStream = new FileOutputStream(headerFile); try { fileHeaderBuilder.build().writeTo(headerOutputStream); headerOutputStream.close(); } catch (IOException e) { throw new SecrecyCipherStreamException("IO exception while writing file header"); } try { c.init(Cipher.ENCRYPT_MODE, vaultFileEncryptionKey, new IvParameterSpec(fileEncryptionNonce)); } catch (InvalidKeyException e) { throw new SecrecyCipherStreamException("Invalid encryption key!"); } catch (InvalidAlgorithmParameterException e) { throw new SecrecyCipherStreamException("Invalid algorithm parameter!"); } BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile), Config.BLOCK_SIZE); return new CipherOutputStream(bufferedOutputStream, c); }
From source file:jfs.sync.encryption.JFSEncryptedStream.java
private void internalClose() throws IOException { delegate.close();//from w w w . j av a 2 s. c om byte[] bytes = delegate.toByteArray(); final byte[] originalBytes = bytes; long l = bytes.length; byte marker = COMPRESSION_NONE; if (log.isDebugEnabled()) { log.debug("close() checking for compressions for"); } // if CompressionThread dt = new CompressionThread(originalBytes) { @Override public void run() { try { ByteArrayOutputStream deflaterStream = new ByteArrayOutputStream(); Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, true); OutputStream dos = new DeflaterOutputStream(deflaterStream, deflater, COMPRESSION_BUFFER_SIZE); dos.write(originalBytes); dos.close(); compressedValue = deflaterStream.toByteArray(); } catch (Exception e) { log.error("run()", e); } // try/catch } // run() }; CompressionThread bt = new CompressionThread(originalBytes) { @Override public void run() { try { if (originalBytes.length > BZIP_MAX_LENGTH) { compressedValue = originalBytes; } else { ByteArrayOutputStream bzipStream = new ByteArrayOutputStream(); OutputStream bos = new BZip2CompressorOutputStream(bzipStream); bos.write(originalBytes); bos.close(); compressedValue = bzipStream.toByteArray(); } // if } catch (Exception e) { log.error("run()", e); } // try/catch } // run() }; CompressionThread lt = new CompressionThread(originalBytes) { /* * // " -a{N}: set compression mode - [0, 1], default: 1 (max)\n" + * " -d{N}: set dictionary - [0,28], default: 23 (8MB)\n" * +" -fb{N}: set number of fast bytes - [5, 273], default: 128\n" * +" -lc{N}: set number of literal context bits - [0, 8], default: 3\n" * +" -lp{N}: set number of literal pos bits - [0, 4], default: 0\n" * +" -pb{N}: set number of pos bits - [0, 4], default: 2\n" * +" -mf{MF_ID}: set Match Finder: [bt2, bt4], default: bt4\n"+" -eos: write End Of Stream marker\n"); */ private int dictionarySize = 1 << 23; private int lc = 3; private int lp = 0; private int pb = 2; private int fb = 128; public int algorithm = 2; public int matchFinderIndex = 1; // 0, 1, 2 @Override public void run() { try { Encoder encoder = new Encoder(); encoder.SetEndMarkerMode(false); encoder.SetAlgorithm(algorithm); // Whatever that means encoder.SetDictionarySize(dictionarySize); encoder.SetNumFastBytes(fb); encoder.SetMatchFinder(matchFinderIndex); encoder.SetLcLpPb(lc, lp, pb); ByteArrayOutputStream lzmaStream = new ByteArrayOutputStream(); ByteArrayInputStream inStream = new ByteArrayInputStream(originalBytes); encoder.WriteCoderProperties(lzmaStream); encoder.Code(inStream, lzmaStream, -1, -1, null); compressedValue = lzmaStream.toByteArray(); } catch (Exception e) { log.error("run()", e); } // try/catch } // run() }; dt.start(); bt.start(); lt.start(); try { dt.join(); bt.join(); lt.join(); } catch (InterruptedException e) { log.error("run()", e); } // try/catch if (dt.compressedValue.length < l) { marker = COMPRESSION_DEFLATE; bytes = dt.compressedValue; l = bytes.length; } // if if (lt.compressedValue.length < l) { marker = COMPRESSION_LZMA; bytes = lt.compressedValue; l = bytes.length; } // if if (bt.compressedValue.length < l) { marker = COMPRESSION_BZIP2; bytes = bt.compressedValue; if (log.isWarnEnabled()) { log.warn("close() using bzip2 and saving " + (l - bytes.length) + " bytes."); } // if l = bytes.length; } // if if (log.isInfoEnabled()) { if (marker == COMPRESSION_NONE) { if (log.isInfoEnabled()) { log.info("close() using no compression"); } // if } // if if (marker == COMPRESSION_LZMA) { if (log.isInfoEnabled()) { log.info("close() using lzma"); } // if } // if } // if ObjectOutputStream oos = new ObjectOutputStream(baseOutputStream); oos.writeByte(marker); oos.writeLong(originalBytes.length); oos.flush(); OutputStream out = baseOutputStream; if (cipher != null) { out = new CipherOutputStream(out, cipher); } // if out.write(bytes); out.close(); delegate = null; baseOutputStream = null; }
From source file:net.jmhertlein.core.crypto.Keys.java
/** * Given a secret key and an output stream, wraps the output stream first in a CipherOutputStream using the given secret key, then in an ObjectOutputStream * * @param key the secret key to use to encrypt data with * @param os the output stream to encrypt and wrap * * @return an ObjectOutputStream whose data will be encrypted with the secret key * @throws NoSuchAlgorithmException/* w ww . j a v a 2 s.c o m*/ * @throws NoSuchPaddingException * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws IOException */ public static ObjectOutputStream getEncryptedObjectOutputStream(SecretKey key, OutputStream os) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException { Cipher outCipher = Cipher.getInstance("AES/CFB8/NoPadding"); outCipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(getKeyBytes(key))); return new ObjectOutputStream(new CipherOutputStream(os, outCipher)); }
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;/*from w w w. j a v a 2s.c o m*/ 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: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 .ja v a 2 s .co 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; }
From source file:org.jets3t.service.security.EncryptionUtil.java
/** * Wraps an output stream in an encrypting cipher stream. * * @param os//from ww w .j a v a 2 s. c om * @return * encrypting cipher output stream. * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException */ public CipherOutputStream encrypt(OutputStream os) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = initEncryptModeCipher(); return new CipherOutputStream(os, cipher); }
From source file:org.jets3t.service.security.EncryptionUtil.java
/** * Wraps an output stream in a decrypting cipher stream. * * @param os/*w w w. ja va 2s .c om*/ * @return * decrypting cipher output stream. * @throws InvalidKeyException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException */ public CipherOutputStream decrypt(OutputStream os) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException { Cipher cipher = initDecryptModeCipher(); return new CipherOutputStream(os, cipher); }